简体   繁体   中英

Using Javascript, how can I convert a Google doc to a PDF file then “slice” it into multiple PDFs?

I would like to replicate VBA code that I wrote for Microsoft Word docs using Google docs and Javascript instead. It would be used in an Angular app that I'm writing.

The VBA code searches for "slice tags" in the document and generates PDF files when it finds them. For example, if a document consists of 15 pages and there are slice tags on pages 4, 7, and 9, the code generates four files: Page1-4.pdf, Page5-7.pdf, Page8-9.pdf, and Page10-15.pdf.

In the Javascript implementation, the steps would be:

  1. Convert the Google doc to a PDF file.
  2. "Slice" the PDF file into multiple PDFs by searching the complete PDF for slice tags.
  3. Place the sliced PDFs in a specified Google Drive folder.

Note that I asked a similar question here .

However, that's a Google Script implementation. What I realized is that in Google Scripts there is no way to address a document on page boundaries. It would be much simpler and cleaner if it did. Instead, I would like to take another approach.

Below is Javascript code that partially addresses step 1. It uses this call:

gapi.client.drive.files.export

However, this does NOT create a PDF file. Rather, it creates a blob of PDF content. Apparently, the expectation is that you transform the blob into an actual file but the Google APIs do not appear to provide a way to do this.

 async function exportDocument(id, mimeType) { let rtrn; try { await gapi.client.drive.files.export( {'fileId': id, 'mimeType': mimeType, 'fields': 'webViewLink', }) .then(function(resp) { // This returns a content blob NOT an actual file rtrn = resp; // TODO: How to transform the blob into an actual file (eg, PDF) }).catch((err) => { throw new Error(err.message); }); } catch (e) { throw new Error('exportDocument: ' + e.message); } return rtrn; } // end exportDocument 

A Blob is a binary representation of the raw data.

Typically, when working with PDFs, the Blob is turned into a File (File is a Blob), and saved to the local filesystem. For an example, see How to convert Blob to File in JavaScript

There is also a 'file-saver' npm library, and, I believe, and Angular/Typescript version as well, if you don't want to do it yourself.

I haven't done it, but I imagine that if the library that you want to use to manipulate the PDF expects a PDF file, you could probably convert the Blob to a PDF without writing it to the filesystem, and then work from there.

BTW, your question has one or more 'close' votes, because you asked a very broad question (ie "how do I write my entire application") instead of asking the targeted question that you really needed answered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM