Print 2 pages per sheet of a document generated with Google App Script

I made a Script that searches for certain PDFs in my email. Then it generates a consolidated document thanks to the PDFApp library and saves it in My Google Drive.
Now I want another document to be generated from that Consolidated PDF document that will help me save paper for printing. And it involves taking the CONSOLIDATED document and printing it in PDF 2 pages per sheet. Thus, if the CONSOLIDATED document is 10 pages, in the new document it will only be 5 pages. I want to do that with Google App Script and I can’t.
I think using https://pdf-lib.js.org/ I could do it, but I’m a newbie and I don’t know how to use that library. Yes, I was able to use the PDFApp library because that library has the script id which I included in the Library and it worked, but https://pdf-lib.js.org/ I don’t know how to use it. Or do you have any idea how I could do it?

I leave you the script that doesn’t work for me to see if you can help me.

// Cargar PDF-LIB desde la URL
function loadPdfLib() {
  const url = 'https://cdn.jsdelivr.net/npm/[email protected]/dist/pdf-lib.min.js';
  const response = UrlFetchApp.fetch(url);
  const jsCode = response.getContentText();
  eval(jsCode);
}

// Función principal para ejecutar el script
function generarAhorroPDF() {
  // Cargar PDF-LIB
  loadPdfLib();

  const folderName = 'RECIBOS DE PAGO';
  const subFolderName = 'RECIBO DE PAGO 2DA QUINCENA DE JUNIO 2024';
  const archivoNombre = 'CONSOLIDADO.pdf';
  const nuevoArchivoNombre = 'AHORRO.pdf';
  
  // Buscar la carpeta principal en Mi Unidad
  const folders = DriveApp.getFoldersByName(folderName);
  if (!folders.hasNext()) {
    throw new Error('No se encontró la carpeta ' + folderName);
  }
  const folder = folders.next();
  
  // Buscar la subcarpeta en la carpeta principal
  const subFolders = folder.getFoldersByName(subFolderName);
  if (!subFolders.hasNext()) {
    throw new Error('No se encontró la subcarpeta ' + subFolderName);
  }
  const subFolder = subFolders.next();
  
  // Buscar el archivo PDF en la subcarpeta
  const files = subFolder.getFilesByName(archivoNombre);
  if (!files.hasNext()) {
    throw new Error('No se encontró el archivo ' + archivoNombre);
  }
  const file = files.next();
  
  // Obtener el contenido del archivo PDF
  const pdfBytes = file.getBlob().getBytes();
  
  // Cargar el documento PDF existente
  PDFDocument.load(pdfBytes).then(pdfDoc => {
    // Crear un nuevo documento PDF
    return PDFDocument.create().then(nuevoPdfDoc => {
      return pdfDoc.getPages().reduce((promise, pagina, index) => {
        return promise.then(() => {
          if (index % 2 === 0) {
            // Crear una nueva página en el nuevo documento
            const nuevaPagina = nuevoPdfDoc.addPage([595.276, 841.890]); // Tamaño de página A4 en puntos
            const { width, height } = nuevaPagina.getSize();
            
            // Dibuja la primera página en la mitad superior
            const { width: page1Width, height: page1Height } = pagina.getSize();
            nuevaPagina.drawPage(pagina, {
              x: 0,
              y: height / 2,
              width: page1Width * 0.5,
              height: page1Height * 0.5,
            });
            
            if (index + 1 < pdfDoc.getPageCount()) {
              // Dibuja la segunda página en la mitad inferior
              const pagina2 = pdfDoc.getPage(index + 1);
              const { width: page2Width, height: page2Height } = pagina2.getSize();
              nuevaPagina.drawPage(pagina2, {
                x: page1Width * 0.5,
                y: height / 2,
                width: page2Width * 0.5,
                height: page2Height * 0.5,
              });
            }
          }
        });
      }, Promise.resolve()).then(() => {
        // Guardar el nuevo archivo PDF
        return nuevoPdfDoc.save().then(nuevoPdfBytes => {
          const nuevoBlob = Utilities.newBlob(nuevoPdfBytes, 'application/pdf', nuevoArchivoNombre);
          
          // Subir el nuevo archivo PDF a la carpeta
          subFolder.createFile(nuevoBlob);
          Logger.log('Archivo ' + nuevoArchivoNombre + ' creado con éxito.');
        });
      });
    });
  }).catch(error => {
    Logger.log('Error al procesar el PDF: ' + error.message);
  });
}

I have tried many things, but I am not sure if I have done it right because I am not an expert.

New contributor

David is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật