我使用html2pdf库生成优惠券。
这适用于在页面中显示为HTML的凭证。
我有一个按钮,可以在点击时触发html2pdf()
功能,提示用户接受PDF下载。
我希望HTML不在页面上显示。我尝试应用position: absolute;
并将HTML放在远离用户的视线之外。不幸的是,PDF然后呈现为空白。
有没有办法实现这个目标?
答案 0 :(得分:4)
只需在html2pdf调用之前和之后切换'element-to-print'的显示属性。
https://jsfiddle.net/bambang3128/u6o6ne41/10/
function toggleDisplay() {
var element = document.getElementById('element-to-print');
if (element.style.display == 'block') {
element.style.display = 'none'
} else {
element.style.display = 'block'
}
console.log('toggleDisplay()');
}
function printPDF() {
var element = document.getElementById('element-to-print');
element.style.display = 'block'
html2pdf(element);
element.style.display = 'none'
console.log('printPDF()');
}
<script src="https://rawgit.com/eKoopmans/html2pdf/master/dist/html2pdf.bundle.min.js"></script>
<div id="element-to-print" hidden>
<h1>This is a hidden div</h1>
This one is hidden div contents.
</div>
<p>
Save the hidden element as PDF.
</p>
<button type="button" onclick="toggleDisplay();">Toggle Display!</button>
<button type="button" onclick="printPDF();">Click Me!</button>
答案 1 :(得分:1)
只需使用 display:none 属性隐藏元素。该元素不会出现在下载的pdf中。
以这个例子为例:
function download() {
var element = document.getElementById("report");
// if you want to show the element in pdf
/*
for showing element in pdf
var hidden = document.querySelector('.hidden');
hidden.style.display = "block";
*/
html2pdf(element)
}
.hidden {
display: none;
}
<script src="https://rawgit.com/eKoopmans/html2pdf/master/dist/html2pdf.bundle.min.js"></script>
<button onclick="download()">Download PDF</button>
<div id="report">
<div class="hidden">Hidden Element</div>
<div>Content to be shown in PDF</div>
</div>
答案 2 :(得分:1)
如果您希望不向用户显示内容来下载pdf,请使用innerHTML
<div id="exportPdf" style="display: none"></div>
style="display: none"
至div
var source = window.document.getElementById("exportPdf").innerHTML;
html2pdf().set(opt).from(source).save();
innerHTML可以解决问题
答案 3 :(得分:0)
你可以使用绝对定位并将你的div wayyyyyy放在屏幕之外,如:top000000000000。
然后在你完成image / pdf时取消div!
答案 4 :(得分:0)
您只需将display:none;
分配给您的元素,如下所示:
<div id="element-to-print" style="display:none">
</div>
<button type="button" (click)="html2pdf()">Download as PDF</button>
&#13;
答案 5 :(得分:0)
代替传递元素,只需将HTML作为字符串传递即可:
const htmlAsString = ReactDOMServer.renderToString(<Row>
<Col md="6">Section 1</Col>
<Col md="6">Section 2</Col>
</Row>);
html2pdf().from(htmlAsString).save();
就我而言,我正在使用ReactJS,所以我会这样做:
{{1}}
答案 6 :(得分:0)
在 VueJS 应用程序的上下文中,我遇到了类似的情况,我只想在生成 PDF 时显示内容。
因此您可以简单地“显示”内容并生成 PDF 并立即将其隐藏。
<html2-pdf>
<section slot="pdf-content" :class="generatingPDF ? 'inline-block' : 'hidden">
// Content goes here
</section>
</html2-pdf>
在一个方法中:
methods: {
async generatePDF(){
try {
this.generatedPDF = true
// generating PDF code here
} catch (e) {
console.log(e)
} finally {
this.generatingPDF = false
}
}
}
根据我的经验,用户不会“闪现”应该隐藏的 pdf 内容。