Last active
June 6, 2023 19:07
-
-
Save eng-rodrigocunha/3af0233714607dc2659bedcdb85b6c35 to your computer and use it in GitHub Desktop.
Merge PDF based on a list of Google Drive PDF links on a spreadsheet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://tanaikech.github.io/2023/01/10/merging-multiple-pdf-files-as-a-single-pdf-file-using-google-apps-script/ | |
async function mergePDF() { | |
// Informe o ID da planilha onde estão os links | |
var planilhaId = "1Iq6DNGk8XkfOX3kp2HDmDb1Ac7vK76brkJc6T6oydNc"; | |
// Informe o nome da planilha que contém os links | |
var nomePlanilha = "LINKS"; | |
// Obter a planilha | |
var planilha = SpreadsheetApp.openById(planilhaId); | |
// Obter a guia da planilha com os links | |
var guia = planilha.getSheetByName(nomePlanilha); | |
// Obter os dados da coluna que contém os links | |
var urls = guia.getRange("A:A").getValues(); | |
//Consolida a lista em um único array | |
urls = [].concat(...urls.reduce((r, a) => { | |
a.forEach((v, i) => (r[i] = r[i] || []).push(v)); | |
return r; | |
}, [])); | |
// Remove valores nulos | |
urls = urls.filter(function (el) { | |
return el[0] != null; | |
}); | |
console.log(JSON.stringify(urls)); | |
const data = urls.map((url) => new Uint8Array(DriveApp.getFileById(getIdFromUrl(url)).getBlob().getBytes())); | |
//const data = urls.map((url) => new Uint8Array(UrlFetchApp.fetch(getIdFromUrl(url)).getContent())); | |
// Merge PDFs. | |
const cdnjs = "https://cdn.jsdelivr.net/npm/pdf-lib/dist/pdf-lib.min.js"; | |
eval(UrlFetchApp.fetch(cdnjs).getContentText()); // Load pdf-lib | |
const setTimeout = function(f, t) { | |
Utilities.sleep(t); | |
return f(); | |
} | |
const pdfDoc = await PDFLib.PDFDocument.create(); | |
for (let i = 0; i < data.length; i++) { | |
const pdfData = await PDFLib.PDFDocument.load(data[i]); | |
const pages = await pdfDoc.copyPages(pdfData, [...Array(pdfData.getPageCount())].map((_, i) => i)); | |
pages.forEach(page => pdfDoc.addPage(page)); | |
} | |
const bytes = await pdfDoc.save(); | |
// Create a PDF file. | |
DriveApp.createFile(Utilities.newBlob([...new Int8Array(bytes)], MimeType.PDF, "sample2.pdf")); | |
} | |
function getIdFromUrl(url) | |
{ | |
console.log(url); | |
var id = url.split('id=')[1]; | |
if(!id) | |
{ | |
id = url.split('/d/')[1]; | |
id = id.split('/edit')[0]; // here we have the id | |
} | |
return id; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment