Nicholas Kajoh
Nicholas Kajoh

Reputation: 1611

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

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?

Upvotes: 9

Views: 13793

Answers (4)

Patris
Patris

Reputation: 83

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>

Upvotes: -1

Sheema
Sheema

Reputation: 61

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

Upvotes: 6

Nicholas Kajoh
Nicholas Kajoh

Reputation: 1611

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!

Upvotes: 4

Mario Santini
Mario Santini

Reputation: 3003

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]");

Upvotes: 0

Related Questions