最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Converting a div with attribute "hidden" to pdf with jsPDF and html2canvas - Stack Overflow

programmeradmin6浏览0评论

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?

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?

Share Improve this question asked Jun 23, 2016 at 16:19 Nicholas KajohNicholas Kajoh 1,6113 gold badges20 silver badges29 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6

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

So with Mario Alexandro Santini's suggestion in the ments, 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!

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

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>
发布评论

评论列表(0)

  1. 暂无评论