簡體   English   中英

通過Google-Apps-Script將Goole文檔轉換為pdf時,如何消除多余的多余頁面?

[英]How to get rid of unwanted extra pages when converting a goole document to pdf via google-apps-script?

我有一個舊腳本(除其他外)將google文檔轉換為pdf。 過去工作正常,但現在文件的pdf版本中出現了兩個額外的空白頁。

我剛剛發現此問題也影響了Google文檔中的“以pdf下載”菜單選項。 在這種情況下,有很多解決方法,但是我需要針對google-apps-script的解決方法。

這篇文章中 ,解決類似問題的方法似乎涉及頁面大小的微調。 我嘗試過類似的方法,但並不適用。 我還嘗試了頁面大小和邊距的其他(隨機)變化,但無濟於事。

下面,我粘貼一個最小的工作示例。 它應該在主驅動器文件夾中創建一個文檔文件“ test”及其pdf版本“ test.pdf”。

任何擺脫兩個額外頁面的幫助將不勝感激。

謝謝

function myFunction() {
  // this function 
  // - creates a google document "test", 
  // - writes "this is a test" inside it
  // - saves and closes the document
  // - creates a pdf version of the document, called "test.pdf"
  //
  // the conversion is ok, except two extra blank pages appear in the pdf version.


  // create google document
  var doc = DocumentApp.create('test');
  var docFile = DriveApp.getFileById( doc.getId() );
  // set margins (I need landscape layout)
  // this is an attempt to a solution, inspired by https://stackoverflow.com/questions/18426817/extra-blank-page-when-converting-html-to-pdf
  var body = doc.getBody();
  body.setPageHeight(595.2).setPageWidth(841.8);   
  var mrg = 40; // in points
  body.setMarginTop(mrg).setMarginBottom(mrg);   
  body.setMarginLeft(mrg).setMarginRight(mrg);   
  // write something
  body.appendParagraph('this is a test').setHeading(DocumentApp.ParagraphHeading.HEADING2).setAlignment(DocumentApp.HorizontalAlignment.CENTER);  
  // save and close file
  doc.saveAndClose();
  // convert file to pdf
  var docblob = docFile.getAs('application/pdf');
  // set pdf name
  docblob.setName("test.pdf");
  // save pdf file
  var file = DriveApp.createFile(docblob);

}

我在8個月前的google產品論壇上的這篇文章中找到了問題的根源和解決方案。

如果未選中視圖->打印布局中的選項,則多余的頁面將顯示在pdf中。 我用我的帳戶和我的同事進行了進一步的測試。 結果是一致的:

  1. 當未查看->打印布局時,文檔的pdf版本中會出現兩個額外的頁面
  2. 當查看->打印布局被選中時,文檔的pdf版本具有預期的頁數。
  3. 此設置還會影響Google Apps腳本中的documentApp服務。 也就是說:僅當選中Google Documents中的“ view-> print layout”選項時,以上腳本才會產生預期的pdf版本。

我不知道這種行為如何成為“功能”,所以我認為這是一個錯誤。 順便說一下,“打印布局”似乎對我的文檔沒有任何可見的影響(除了弄亂pdf版本)。 令我驚訝的是,八個月后,該錯誤仍然存​​在。

上面的數字3讓我感到驚訝,因為我認為在任何Google文檔中手動設置的選項不會影響我的腳本。 我目前正在尋找一種從腳本內部設置“打印布局”選項的方法。 到目前為止,我還沒有運氣。

暫無
暫無

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

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