Converting a div with attribute "hidden" to pdf with jsPDF and html2canvas
Asked Answered
L

4

9

I'm using jsPDF and html2canvas to convert a div to pdf:

<a onclick="makePdf()">PDF</a>
<div id="divToPdf">Some content here</div>

However I don't want my div displayed on the screen. I tried using hidden property to hide the div:

<a onclick="makePdf()">PDF</a>
<div id="divToPdf" hidden>Some content here</div>

The problem is that the hidden property results in a blank pdf document. How do I go about hiding the div without this problem?

Luckey answered 23/6, 2016 at 16:19 Comment(0)
R
6

To hide an HTML tag; add this attribute tag data-html2canvas-ignore="true" instead of the hidden.

Rania answered 20/12, 2018 at 11:24 Comment(0)
L
4

So with Mario Alexandro Santini's suggestion in the comments, I was able to solve the problem. I used jquery to unhide the div in my makePdf() function then hide it again after jsPDF and html2canvas had done their "magic":

function makePdf() {
    $("#divToPdf").attr("hidden", false);
    ...
    $("#divToPdf").attr("hidden", true);
}

Thanks guys!

Luckey answered 24/6, 2016 at 10:9 Comment(0)
M
0

You could change the layout of your page on different media through css.

This is true for printing too.

So you could write a dedicated stylesheet that is valid only when you print the page in pdf.

Please have a look at:

@media print {
   ...
}

For your example you could use a code like:

@media print {
   div[hidden] {
      display: block;
   }
   ...
}

This should select the div with hidden attribute and made those visible.

If you prefere the programatic approach then you could get all div in the page with attribute hidden and remove the attribute, print your document, than put the attribute back.

You could use something like:

var hideDivs = document.querySelectorAll("div[hidden]");
Menton answered 23/6, 2016 at 16:29 Comment(3)
I tried both. None worked. I'm actually converting the div to pdf, not printing it.The media query in your answer seems to be for printing.Luckey
I don't know how your makePdf() works, if you use some kind of lib to directly convert the page content to pdf, then you have to use the second way: changing the page with the querySelectorAll before call the makePdf().Menton
Okay. Cool. Thanks!Luckey
H
-1

I think the cleanest solution is to use hidden on a parent div, and use jsPDF to print the div inside.

<div hidden>
    <div id="divToPdf">Some content here</div>
</div>
Holzer answered 27/3 at 14:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.