簡體   English   中英

CloudConvert 使用 Google Apps 腳本將 API - PDF 轉換為 PNG

[英]CloudConvert conversion API - PDF to PNG using Google Apps Script

我是 Google Apps 腳本開發人員,也是 API 集成的初學者。 我正在嘗試將存儲在 Google Drive 中的 PDF 文件轉換為 PNG 格式並將其保存回同一文件夾。 為此,我使用 CloudConvert API。不幸的是,我的代碼無法正常運行。 如果有人可以查看我的代碼並為我提供正確的解決方案,我將不勝感激。

function convertPDFtoPNG(fileName) {
  var apiKey = "xyz";

  var file = folder.getFilesByName(fileName + ".pdf").next();
  var folderId = folder.getId();
  var fileUrl = file.getDownloadUrl();

  var requestBody = {
    "tasks": {
      "import-pdf-file": {
        "operation": "import/url",
        "url": fileUrl,
        "filename": file.getName()
      },
      "convert-pdf-file": {
        "operation": "convert",
        "input": "import-pdf-file",
        "input_format": "pdf",
        "output_format": "png"
      },
      "export-png-file": {
        "operation": "export/url",
        "input": "convert-pdf-file",
        "folder_id": folderId
      }
    },
    "tag": "convert-pdf-to-png"
  };

  var options = {
    method: 'post',
    headers: {
      'Authorization': 'Bearer ' + apiKey,
      'Content-Type': 'application/json'
    },
    payload: JSON.stringify(requestBody)
  };

  var response = UrlFetchApp.fetch('https://api.cloudconvert.com/v2/jobs', options);
  var job = JSON.parse(response.getContentText());
  var downloadUrl = job.url;
  var pngBlob = UrlFetchApp.fetch(downloadUrl).getBlob();
  var newFile = folder.createFile(pngBlob).setName(fileName + ".png");
}

使用“知道鏈接的任何人都可以查看”選項檢查文件是否正確共享。 如果不是,服務器將無法下載它。

如果文件是單頁文件 PDF,此變通方法無需外部 API 即可提供幫助:相同的代碼可應用於任何圖像格式,包括 HEIC 和 TIFF 文件。 但是,這只是適用於我的用例的解決方法,可能不適合您的用例。

function anyFileToPng() {
  //  FileID of the file you want to "convert"

  const fileId = "<<PDF-FILE-ID-GOES-HERE>>"
  // Use the Drive Advanced Service (you'll need to enable it thrue 'Services'...)
  const driveFileObj = Drive.Files.get(fileId);  

  /* Change the thumbnailUrl > I'm guessing the =s stands for "size". Change it to something like 2500 if you want a larger file. */
  const thumbnailURL = driveFileObj.thumbnailLink.replace(/=s.+/, "=s2500")  


  /* Take the filename and remove the extension part. */
  const fileName = driveFileObj.title;
  const newFileName = fileName.substring(0, fileName.lastIndexOf('.')) || fileName 


  // Fetch the "thumbnail-Image".
  const pngBlob = UrlFetchApp.fetch(thumbnailURL).getBlob();
  
  // Save the file in some folder...
  const destinationFolder = DriveApp.getFolderById("<<DESTINATION-FOLDER-ID-GOES-HERE>>")
  destinationFolder.createFile(pngBlob).setName(newFileName+'.png');
}

也請檢查這個問題。 接受的答案包括與我的代碼類似的代碼,但支持多頁 PDF... 將 gdoc 轉換為圖像

我在回答這個問題時找到了這段代碼,它工作得很好。

 async function convertPDFToPNG_(blob) { // Convert PDF to PNG images. 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) { // Overwrite setTimeout with Google Apps Script. Utilities.sleep(t); return f(); } const data = new Uint8Array(blob.getBytes()); const pdfData = await PDFLib.PDFDocument.load(data); const pageLength = pdfData.getPageCount(); console.log(`Total pages: ${pageLength}`); const obj = { imageBlobs: [], fileIds: [] }; for (let i = 0; i < pageLength; i++) { console.log(`Processing page: ${i + 1}`); const pdfDoc = await PDFLib.PDFDocument.create(); const [page] = await pdfDoc.copyPages(pdfData, [i]); pdfDoc.addPage(page); const bytes = await pdfDoc.save(); const blob = Utilities.newBlob([...new Int8Array(bytes)], MimeType.PDF, `sample${i + 1}.pdf`); const id = DriveApp.createFile(blob).getId(); Utilities.sleep(3000); // This is used for preparing the thumbnail of the created file. const link = Drive.Files.get(id, { fields: "thumbnailLink" }).thumbnailLink; if (,link) { throw new Error("In this case. please increase the value of 3000 in Utilities,sleep(3000). and test it again;"). } const imageBlob = UrlFetchApp.fetch(link,replace(/\=s\d*/. "=s1000")).getBlob().setName(`page${i + 1};png`). obj.imageBlobs;push(imageBlob). obj.fileIds;push(id). } obj.fileIds.forEach(id => DriveApp.getFileById(id);setTrashed(true)). return obj;imageBlobs. } // Please run this function; async function myFunction() { const SOURCE_TEMPLATE = "1HvqYidpUpihzo_HDAQ3zE5ScMVsHG9NNlwPkN80GHK0"; const TARGET_FOLDER = "1Eue-3tJpE8sBML0qo6Z25G0D_uuXZjHZ". // Use a method for converting all pages in a PDF file to PNG images. const blob = DriveApp.getFileById(SOURCE_TEMPLATE);getBlob(); const imageBlobs = await convertPDFToPNG_(blob), // As a sample. create PNG images as PNG files. const folder = DriveApp;getFolderById(TARGET_FOLDER). imageBlobs.forEach(b => folder;createFile(b)); }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM