Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

196
Views
Cómo guardar PDF desde HTML con la misma representación en el script de la aplicación

Necesito guardar una página web HTML como pdf en mi Google Drive. Estoy usando el script de la aplicación.
Sin embargo, el PDF se representa de manera diferente a la página HTLM. Necesito que el PDF sea el mismo que el HTML.

Aquí hay una pantalla de impresión del HTML

ingrese la descripción de la imagen aquí

y aquí está mi código:

 function downloadFile() { var fileURL = "http....." var folder = "primes" var fileName = ""; var fileSize = ""; var response = UrlFetchApp.fetch(fileURL, { headers: { Authorization: 'Bearer ' + ScriptApp.getOAuthToken() }, }) var htmlBody = response.getContentText(); var rc = response.getResponseCode(); if (rc == 200) { var blob = Utilities.newBlob(htmlBody, MimeType.HTML).getAs('application/pdf').setName('Nota.pdf'); var folder = DriveApp.getFolderById("1gBA8YCs3PH7v7CNl3nlsjNqYzhOxhjYa"); if(folder != null){ var file = folder.createFile(blob); fileName = file.getName() fileSize = file.getSize() } } var fileInfo = {'rc':rc,"filename": fileName, "fileSize":fileSize} Logger.log(fileInfo) }

!!!!¡¡¡¡¡¡ACTUALIZAR!!!!!!

Esta es la salida que estoy obteniendo:

ingrese la descripción de la imagen aquí

Sé que es posible guardar este PDF correctamente, porque si usa una extensión de Chrome llamada HTML TO PDF, se convierte correctamente como se muestra en la siguiente figura

ingrese la descripción de la imagen aquí

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

La mejor manera de hacerlo es a través del titiritero. Puppeteer es una biblioteca de nodejs que puede iniciar un navegador web sin interfaz.

 const puppeteer = require('puppeteer') // I found these sizes work best when outputting to A4 format const browser = await puppeteer.launch({ headless: true, args: [`--window-size=794,1123`], defaultViewport: { width: 980, height: 1386 } }); const page = await browser.newPage(); // Convert the html string to a raw string to keep any special characters as plain text const doc = String.raw`${YOUR STRING}`; // I found that it works better if you first search a page and then set the content. await page.goto("https://google.com") // set the html content of the page await page.setContent(doc); let file = “File.pdf”`; let path = “output path”; // saves a pdf to the provided path const pdf = await page.pdf({ path: path, scale: 0.8, displayHeaderFooter: true, printBackground: true, margin: { top: 80, bottom: 80, left: 30, right: 30 } }); await browser.close();

Pro: ofrece una salida realmente limpia con texto seleccionable Contra: debe ejecutar este código en un servidor nodejs para obtener el mejor resultado

Para obtener más documentación sobre el titiritero, consulte https://pptr.dev/#?product=Puppeteer&version=v10.4.0&show=api-pagepdfoptions

about 4 years ago · Juan Pablo Isaza Report

0

Simplemente use Chrome desde su línea de comandos, sin necesidad de marionetas ni ninguna otra aplicación.

ingrese la descripción de la imagen aquí

 --headless --disable-gpu --enable-logging --print-to-pdf="%UserProfile%\Documents\Demofile.pdf" --disable-extensions --print-to-pdf-no-header --disable-popup-blocking --run-all-compositor-stages-before-draw --disable-checker-imaging https://bling.com.br/doc.view.php?id=2565744b051b9f1d3177c30ccf1e65b2

PROs Exactamente como HTML se representa en un navegador

CONTRAS Exactamente como las páginas HTML se guardarían como PDF RETRATO desde un navegador (el valor predeterminado de la línea de comando es horizontal = falso), por lo que para cambiar el diseño necesita otro método.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!