paper background image does not appear in exported png/svg/jpeg file - jointjs

paper.toPNG(function (dataURI) {
const link = document.createElement("a");
link.href = dataURI;
link.setAttribute("download", 'fileName.png');
document.body.appendChild(link);
link.click();
});
The above code is use to export in PNG format, but the paper background image is not applied to the downloaded image
The background image is applied as flows
paper.drawBackground({
image: 'image url',
position: 'center',
repeat: 'no-repeat',
size: 'cover',
opacity: 1
});

Related

page.url() does not have page's url and return blank value

I want to get the page URL and generate PDF according to that new page is rendered, but when I load the new page the page.url() returns a blank value.
Anyone encountered a similar issue or know how to solve this issue thanks in advance.
// Generate PDF file
(async () => {
// The location
const browser = await puppeteer.launch({
headless: true,
slowMo: 100,
});
var page = (await browser.pages())[0];
const url = (await page.url()); // page.url should return me the current URL
for example:
"http://localhost:5000/articles/tv"
console.log(url); // This returns blank value.
await page.goto(url, { waitUntil: "load" });
await page.pdf({
path: "page.pdf",
format: "A4",
printBackground: true,
scale: 0.5,
displayHeaderFooter: false,
margin: { bottom: "50px" },
});
await browser.close();
})();
// Downloading PDF files
app.get("/downloadPDF", (req, res) => {
// express.js
res.download("./page.pdf");
});
//
From the source you provided above, the page isn't loading any URL. Its URL is simply about:blank, So you'll get blank value.
var page = (await browser.pages())[0];
This should be:
var page = await browser.newPage()
await page.goto(someURL)
or maybe you want to use the already opened tab in Puppeteer.
var [page] = await browser.pages()
await page.goto(someURL)
What are you trying to get or achieve by doing this?
If you want to generate PDF from a URL, you can use page.goto(url) and then page.pdf().
await page.goto('https://en.wikipedia.org/wiki/PDF')
await page.pdf({
path: "page.pdf",
format: "A4",
printBackground: true,
scale: 0.5,
displayHeaderFooter: false,
margin: { bottom: "50px" },
})
But if you're trying to print HTML tags, without navigating to any url, you can simply page.setContent() and then page.pdf() to print PDF from it.
const html = '<h3>PDF</h3><p>PDF is Portable Document Format</p>'
await page.setContent(html)
await page.pdf({
path: "page.pdf",
format: "A4",
printBackground: true,
scale: 0.5,
displayHeaderFooter: false,
margin: { bottom: "50px" },
})

Reduce size of headless puppeteer screenshot

I'm using a lambda function to launch puppeteer with headless chrome. I'm able to take a picture and save it to an s3 bucket, but the image is way too big. I was originally setting the viewport to default, but the image was still coming out as 1520 X 1520.
Here is my current code to launch the headless browser and take the screenshot.
const browser = await chromium.puppeteer.launch({
executablePath: await chromium.executablePath,
headless: chromium.headless,
args: chromium.args,
defaultViewport: { width: 800, height: 600, deviceScaleFactor: 2 },
ignoreHTTPSErrors: true,
});
const body = isJson(event.data ? event.data : event.body);
const timeStamp = Date.now();
const HandleBars = require("handlebars");
const bucketForTemplates = {
Bucket: templateBucket,
Key: `${body.template}.hbs`,
};
const file = await s3.getObject(bucketForTemplates).promise();
const template = HandleBars.compile(file.Body.toString());
const renderedPage = template(body);
const page = await browser.newPage();
await page.setViewport({ deviceScaleFactor: 2 });
await page.setContent(renderedPage);
//wait for page to load
await page.waitForSelector("#image");
const image = await page.$("#image");
const box = await image.boundingBox();
const x = box["x"];
const y = box["y"];
const w = box["width"];
const h = box["height"];
const buffer = await page.screenshot({
type: "jpeg",
clip: { x: x, y: y, width: w, height: h },
});
await page.close();
await browser.close();
//save image to s3.
The div I am taking a picture of has a set width of 760px and height of 760px but the screenshot is 1520 X 1520.
How do I reduce the size of the image to not be so big?
You launch puppeteer with deviceScaleFactor: 2 viewport setting:
const browser = await chromium.puppeteer.launch({
defaultViewport: { width: 800, height: 600, deviceScaleFactor: 2 }, // <----
});
According to docs, it "can be thought of as DPR", or device pixel ratio, thus enlarging resolution by 2.
The default for this setting is 1, which is what you'd like to use to get the screenshot of a correct size.

PDFToolKit is sending weird data

I have installed PDFKit for node.js. When i call my method to download a PDF file, i get this kind of characers on my browser:
xœU»nÜ0ìùüËûâ’Œ+8Ò¹.H‘œOn|Eà¿ï!ï> AÔ’”†ÃåÌŠ#áºa4Χð+ðÕ؇ýe£ªMfç)av
This is my code:
var doc = new PDFDocument({ layout: 'landscape' });
doc.pipe(res);
doc.moveDown(1);
doc.text(reportName, { align: "center" });
doc.text(bNames.join(','), { align: "center" });
doc.text(dateFrom + " - " + dateTo, { align: "center" });
doc.moveDown(2);
const table0 = {
headers: allNames,
rows: allData
};
doc.table(table0, {
prepareHeader: () => doc.font('Helvetica-Bold').fontSize(10),
prepareRow: (row, i) => doc.font('Helvetica').fontSize(10)
});
doc.end();
Is there something else i have to tell PDFKit to work right?
EDIT1:
I am running this code on my backend and sending it to my frontend so i can download it there
If you want a PDF response straight to the browser, you need to add the header so it understands the binary data.
Set this before the response is piped.
res.setHeader('Content-type', 'application/pdf')

how to save png format to pdf format using pdfkit in nodejs [code included]

I am doing a server side coding and wanted to convert the file extension to pdf extension and it should be saved in S3. Any suggestions will be valuable. I am a beginner in this area, so apologies if the question offends anyone.
uploadFiles: (files, bucketName, path) =>{
return new Promise(async function(resolve, reject) {
var doc = new PDFDocument()
var file = files[0];
let filename = file.originalFilename;
var file_path = file.path;
doc.image(file_path, {
fit: [250, 300],
align: 'center',
valign: 'center'
});
//doc.y = 300
//doc.pipe(res)
// console.log('img',img);
var path = 'images/'+ file.originalFilename;
console.log( 'path',path);
var path = await uploadFiles(file, bucketName, path);
resolve(path);
//doc.end()
});
}
};
Try by looking into this example. You probably would need to save the PDF on disk before uploading it to a bucket. Also try adding the X and Y position to where the image will be placed on the PDF.
router.route('/generate.pdf')
.post(multiparty(), function(req,res,next){
// Creates a new instace of a Pdf Document Model
var pdfDocument = new PdfDocument(req.body);
// New Instance of the PDFKit PDFDOCUMENT
var pdf = new PDFDocument({
size: 'LETTER',
info: {
Title: 'title',
Author: 'me',
}
});
// Top Logo
pdf.image('./logo.jpg', 500, 35, {width: 60});
// Document Top Title
pdf.fontSize(14).text('Some Title', {
align: 'center' });
var fileName = 'some.pdf';
// Stream contents to a file
pdf.pipe(fs.createWriteStream(fileName))
.on('finish', function () {
console.log('PDF closed');
});
// Close PDF and write file.
pdf.pipe(res);
pdf.end();
});

PhantomJS package - converting html to pdf issue

I'm using PhantomJS Package for converting an HTML page to pdf. I'm using below code for generating the pdf file.
const phantom = require('phantom');
(async function() {
const instance = await phantom.create();
const page = await instance.createPage();
await page.property('viewportSize', { width: 1024, height: 600 });
const status = await page.open('https://stackoverflow.com/');
console.log(`Page opened with status [${status}].`);
await page.render('stackoverflow.pdf');
console.log(`File created at [./stackoverflow.pdf]`);
await instance.exit();
})()
Using above code pdf generated successfully. But the page of the generated pdf is too long not A4 size. Can you please let me how to resolve this issue.
To view the generated PDF - https://drive.google.com/file/d/1RfKZd5ZPFpYDOkiPR6mFt_5M0BhRbTXQ/view
You should set the page paperSize.
paperSize {object}
This property defines the size of the web page when rendered as a PDF.
page.paperSize = {
width: '8.267in',
height: '11.692in',
margin: {
top: '50px',
left: '20px'
}
};

Resources