UPDATE:
I need to save an HTML webpage as a pdf in my google Drive. I am using app script.
However, the PDF is rendered differently from the HTLM page. I need the PDF to be the same as the HTML. FROM RESEARCH I DISCOVERED THAT EXTERNAL CSS IS NOT RENDERED PROPERLY, ONLY INLINE CSS.
I have an HTML page and I need to transform the external CSS into inline CSS. I need to do this using an app script.
Is it possible?
EDIT: MORE DETAILS -- HERE IS MY FUNCTION IN APPSCRIPT AND MY HTML CSS HEADER
function downloadFile() {
var fileURL = "https://www.....
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)
}
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Bling - </title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://www.bling.com.br/libs/jquery-1.9.1.min.js" type="text/javascript"></script>
<script type="text/javascript" src="https://www.bling.com.br/libs/utils-1632934481.js"></script> <link rel="stylesheet" type="text/css" href="https://www.bling.com.br/styles/danfe.css" />
<style>
table.grid tr td{
/*padding:2px;*/
The output I get is totally not rendered correctly
CodePudding user response:
Just replace the external css with the actual value with padded style
tags.
Script:
var htmlBody = response.getContentText();
// replace external css with the actual css, padded with style tags
var externalCss = `<link rel="stylesheet" type="text/css" href="https://www.bling.com.br/styles/danfe.css" />`;
htmlBody = htmlBody.replace(externalCss, `<style>${UrlFetchApp.fetch('https://www.bling.com.br/styles/danfe.css').getContentText()}</style>`)
var rc = response.getResponseCode();
If this doesn't work due to captcha. (I'm not sure if captcha will cause you some issues when fetching). Copy the actual css (pad it with tags), save it in a file and include it in your string before converting to blob by using:
HtmlService.createHtmlOutputFromFile(filename).getContent()