我有以下html代码:
<!DOCTYPE html>
<html>
<body>
<p>don't print this to pdf</p>
<div id="pdf">
<p><font size="3" color="red">print this to pdf</font></p>
</div>
</body>
</html>
我想要做的就是将在 div 中找到的任何 id 为“pdf”的内容打印为 pdf。这必须使用 JavaScript 完成。然后应自动下载“pdf”文档,文件名为“foobar.pdf”
我一直在使用 jspdf 来做到这一点,但它唯一的功能是“文本”,它只接受字符串值。我想将 HTML 提交到 jspdf,而不是文本。
fromHTML
函数;请参阅“HTML 渲染器”示例:mrrio.github.io/jsPDF
jsPDF 能够使用插件。为了使它能够打印 HTML,您必须包含某些插件,因此必须执行以下操作:
转到 https://github.com/MrRio/jsPDF 并下载最新版本。在您的项目中包含以下脚本: jspdf.js jspdf.plugin.from_html.js jspdf.plugin.split_text_to_size.js jspdf.plugin.standard_fonts_metrics.js
如果你想忽略某些元素,你必须用一个 ID 标记它们,然后你可以在 jsPDF 的特殊元素处理程序中忽略它。因此,您的 HTML 应如下所示:
<!DOCTYPE html>
<html>
<body>
<p id="ignorePDF">don't print this to pdf</p>
<div>
<p><font size="3" color="red">print this to pdf</font></p>
</div>
</body>
</html>
然后使用以下 JavaScript 代码在弹出窗口中打开创建的 PDF:
var doc = new jsPDF();
var elementHandler = {
'#ignorePDF': function (element, renderer) {
return true;
}
};
var source = window.document.getElementsByTagName("body")[0];
doc.fromHTML(
source,
15,
15,
{
'width': 180,'elementHandlers': elementHandler
});
doc.output("dataurlnewwindow");
对我来说,这创建了一个漂亮而整洁的 PDF,其中仅包含“将其打印为 pdf”这一行。
请注意,特殊元素处理程序仅处理当前版本中的 ID,这也在 GitHub Issue 中说明。它指出:
因为匹配是针对节点树中的每个元素完成的,所以我的愿望是让它尽可能快。在这种情况下,这意味着“仅匹配元素 ID”。元素 ID 仍然以 jQuery 样式“#id”完成,但这并不意味着支持所有 jQuery 选择器。
因此,用“.ignorePDF”之类的类选择器替换“#ignorePDF”对我不起作用。相反,您必须为每个要忽略的元素添加相同的处理程序,例如:
var elementHandler = {
'#ignoreElement': function (element, renderer) {
return true;
},
'#anotherIdToBeIgnored': function (element, renderer) {
return true;
}
};
从 examples 中还指出,可以选择像“a”或“li”这样的标签。不过,对于大多数用例来说,这可能有点不受限制:
我们支持特殊的元素处理程序。使用 jQuery 样式的 ID 选择器为 ID 或节点名称注册它们。 (“#iAmID”、“div”、“span”等)目前不支持任何其他类型的选择器(类、复合)。
要添加的一件非常重要的事情是您丢失了所有样式信息 (CSS)。幸运的是,jsPDF 能够很好地格式化 h1、h2、h3 等,这对我的目的来说已经足够了。此外,它只会打印文本节点内的文本,这意味着它不会打印 textareas 等的值。例子:
<body>
<ul>
<!-- This is printed as the element contains a textnode -->
<li>Print me!</li>
</ul>
<div>
<!-- This is not printed because jsPDF doesn't deal with the value attribute -->
<input type="textarea" value="Please print me, too!">
</div>
</body>
这是简单的解决方案。这对我有用。您可以使用 javascript 打印概念并将其简单地保存为 pdf。
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$("#btnPrint").live("click", function () {
var divContents = $("#dvContainer").html();
var printWindow = window.open('', '', 'height=400,width=800');
printWindow.document.write('<html><head><title>DIV Contents</title>');
printWindow.document.write('</head><body >');
printWindow.document.write(divContents);
printWindow.document.write('</body></html>');
printWindow.document.close();
printWindow.print();
});
</script>
</head>
<body>
<form id="form1">
<div id="dvContainer">
This content needs to be printed.
</div>
<input type="button" value="Print Div Contents" id="btnPrint" />
</form>
</body>
</html>
没有依赖,纯 JS
要添加 CSS 或图像 - 不要使用相对 URL,请使用完整 URL http://...domain.../path.css 左右。它创建单独的 HTML 文档,并且没有主要内容的上下文。
您还可以将图像嵌入为 base64
这已经为我服务了多年:
export default function printDiv({divId, title}) {
let mywindow = window.open('', 'PRINT', 'height=650,width=900,top=100,left=150');
mywindow.document.write(`<html><head><title>${title}</title>`);
mywindow.document.write('</head><body >');
mywindow.document.write(document.getElementById(divId).innerHTML);
mywindow.document.write('</body></html>');
mywindow.document.close(); // necessary for IE >= 10
mywindow.focus(); // necessary for IE >= 10*/
mywindow.print();
mywindow.close();
return true;
}
当然,这将打开打印对话框,用户必须知道她/他可以选择打印到 pdf 选项以获取 pdf。可能预先选择了打印机,如果用户确认可以实际打印此文档。为了避免这种情况并提供没有任何附加内容的 PDF,您需要制作 PDF 文件。可能在服务器端。您可以拥有仅包含发票的小型 html 页面,并将其转换为带有无头 chrome 的 PDF 文件。使用 puppeteer 超级简单。无需安装/配置 chrome,只需安装 npm 包 puppeteer(由 chrome 团队管理)并运行它。请记住,这实际上会在没有 GUI 的情况下启动真正的 chrome,因此您需要为此准备一些 RAM 和 CPU。大多数服务器都可以在足够低的流量下使用。这是代码示例,但这必须在 BACKEND 上运行。节点。而且它的调用速度很慢,它是资源密集型调用。您不应该在 api 调用上运行它,而是在创建发票之后 - 为其创建 pdf 并存储,如果尚未生成 pdf,只需显示消息以在几分钟后重试。
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://your-domain.com/path-to-invoice', {
waitUntil: 'networkidle2',
});
await page.pdf({ path: 'invoice-file-path.pdf', format: 'a4' });
await browser.close();
})();
在此处了解更多信息:https://pptr.dev/
<body >
处的额外间距,它需要这个:P
如果您需要下载特定页面的 pdf,只需添加这样的按钮
<h4 onclick="window.print();"> Print </h4>
使用 window.print() 打印所有页面,而不仅仅是一个 div
document.querySelector("#myIframe").contentWindow.print()
您可以使用 autoPrint() 并将输出设置为“dataurlnewwindow”,如下所示:
function printPDF() {
var printDoc = new jsPDF();
printDoc.fromHTML($('#pdf').get(0), 10, 10, {'width': 180});
printDoc.autoPrint();
printDoc.output("dataurlnewwindow"); // this opens a new popup, after this the PDF opens the print window view but there are browser inconsistencies with how this is handled
}
如前所述,您应该使用 jsPDF 和 html2canvas。我还在 jsPDF 问题中找到了一个功能,它可以自动将您的 pdf 拆分为多个页面 (sources)
function makePDF() {
var quotes = document.getElementById('container-fluid');
html2canvas(quotes, {
onrendered: function(canvas) {
//! MAKE YOUR PDF
var pdf = new jsPDF('p', 'pt', 'letter');
for (var i = 0; i <= quotes.clientHeight/980; i++) {
//! This is all just html2canvas stuff
var srcImg = canvas;
var sX = 0;
var sY = 980*i; // start 980 pixels down for every new page
var sWidth = 900;
var sHeight = 980;
var dX = 0;
var dY = 0;
var dWidth = 900;
var dHeight = 980;
window.onePageCanvas = document.createElement("canvas");
onePageCanvas.setAttribute('width', 900);
onePageCanvas.setAttribute('height', 980);
var ctx = onePageCanvas.getContext('2d');
// details on this usage of this function:
// https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images#Slicing
ctx.drawImage(srcImg,sX,sY,sWidth,sHeight,dX,dY,dWidth,dHeight);
// document.body.appendChild(canvas);
var canvasDataURL = onePageCanvas.toDataURL("image/png", 1.0);
var width = onePageCanvas.width;
var height = onePageCanvas.clientHeight;
//! If we're on anything other than the first page,
// add another page
if (i > 0) {
pdf.addPage(612, 791); //8.5" x 11" in pts (in*72)
}
//! now we declare that we're working on that page
pdf.setPage(i+1);
//! now we add content to that page!
pdf.addImage(canvasDataURL, 'PNG', 20, 40, (width*.62), (height*.62));
}
//! after the for loop is finished running, we save the pdf.
pdf.save('test.pdf');
}
});
}
我使用 jspdf 和 html2canvas 进行 css 渲染,并导出特定 div 的内容,因为这是我的代码
$(document).ready(function () {
let btn=$('#c-oreder-preview');
btn.text('download');
btn.on('click',()=> {
$('#c-invoice').modal('show');
setTimeout(function () {
html2canvas(document.querySelector("#c-print")).then(canvas => {
//$("#previewBeforeDownload").html(canvas);
var imgData = canvas.toDataURL("image/jpeg",1);
var pdf = new jsPDF("p", "mm", "a4");
var pageWidth = pdf.internal.pageSize.getWidth();
var pageHeight = pdf.internal.pageSize.getHeight();
var imageWidth = canvas.width;
var imageHeight = canvas.height;
var ratio = imageWidth/imageHeight >= pageWidth/pageHeight ? pageWidth/imageWidth : pageHeight/imageHeight;
//pdf = new jsPDF(this.state.orientation, undefined, format);
pdf.addImage(imgData, 'JPEG', 0, 0, imageWidth * ratio, imageHeight * ratio);
pdf.save("invoice.pdf");
//$("#previewBeforeDownload").hide();
$('#c-invoice').modal('hide');
});
},500);
});
});
一种方法是使用 window.print() 函数。不需要任何库
优点
1.无需外部库。
2.我们也可以只打印身体的选定部位。
3.没有css冲突和js问题。
4.核心html/js功能
---只需添加以下代码
CSS 到
@media print {
body * {
visibility: hidden; // part to hide at the time of print
-webkit-print-color-adjust: exact !important; // not necessary use
if colors not visible
}
#printBtn {
visibility: hidden !important; // To hide
}
#page-wrapper * {
visibility: visible; // Print only required part
text-align: left;
-webkit-print-color-adjust: exact !important;
}
}
JS 代码 - 在 btn 点击时调用 bewlow 函数
$scope.printWindow = function () {
window.print()
}
注意:在每个 css 对象中使用 !important
例子 -
.legend {
background: #9DD2E2 !important;
}
使用 pdfMake.js 和 this Gist。
(我找到了 Gist here 以及包 html-to-pdfmake 的链接,我最终暂时没有使用它。)
在 npm install pdfmake
并将 Gist 保存在 htmlToPdf.js
之后,我像这样使用它:
const pdfMakeX = require('pdfmake/build/pdfmake.js');
const pdfFontsX = require('pdfmake-unicode/dist/pdfmake-unicode.js');
pdfMakeX.vfs = pdfFontsX.pdfMake.vfs;
import * as pdfMake from 'pdfmake/build/pdfmake';
import htmlToPdf from './htmlToPdf.js';
var docDef = htmlToPdf(`<b>Sample</b>`);
pdfMake.createPdf({content:docDef}).download('sample.pdf');
评论:
我的用例是从 Markdown 文档(使用 markdown-it)创建相关的 html,然后生成 pdf,并上传其二进制内容(我可以使用 pdfMake 的 getBuffer() 函数获取),所有这些都来自浏览器。对于这种 html,生成的 pdf 比我尝试过的其他解决方案更好。
我对接受的答案中建议的从 jsPDF.fromHTML() 得到的结果不满意,因为该解决方案很容易被我的 HTML 中的特殊字符混淆,这些字符显然被解释为一种标记并完全弄乱了生成的 PDF。
使用基于画布的解决方案(如已弃用的 jsPDF.from_html() 函数,不要与接受的答案中的那个混淆)对我来说不是一种选择,因为我希望生成的 PDF 中的文本是可粘贴的,而基于画布的解决方案生成基于位图的 PDF。
像 md-to-pdf 这样的 pdf 转换器的直接降价仅适用于服务器端,对我不起作用。
使用浏览器的打印功能对我不起作用,因为我不想显示生成的 PDF 而是上传其二进制内容。
我能够让 jsPDF 从 div 打印动态创建的表。
$(document).ready(function() {
$("#pdfDiv").click(function() {
var pdf = new jsPDF('p','pt','letter');
var specialElementHandlers = {
'#rentalListCan': function (element, renderer) {
return true;
}
};
pdf.addHTML($('#rentalListCan').first(), function() {
pdf.save("caravan.pdf");
});
});
});
与 Chrome 和 Firefox 一起使用效果很好......格式在 IE 中都被炸毁了。
我还包括了这些:
<script src="js/jspdf.js"></script>
<script src="js/jspdf.plugin.from_html.js"></script>
<script src="js/jspdf.plugin.addhtml.js"></script>
<script src="//mrrio.github.io/jsPDF/dist/jspdf.debug.js"></script>
<script src="http://html2canvas.hertzen.com/build/html2canvas.js"></script>
<script type="text/javascript" src="./libs/FileSaver.js/FileSaver.js"></script>
<script type="text/javascript" src="./libs/Blob.js/Blob.js"></script>
<script type="text/javascript" src="./libs/deflate.js"></script>
<script type="text/javascript" src="./libs/adler32cs.js/adler32cs.js"></script>
<script type="text/javascript" src="js/jspdf.plugin.addimage.js"></script>
<script type="text/javascript" src="js/jspdf.plugin.sillysvgrenderer.js"></script>
<script type="text/javascript" src="js/jspdf.plugin.split_text_to_size.js"></script>
<script type="text/javascript" src="js/jspdf.plugin.standard_fonts_metrics.js"></script>
如果要导出表格,可以查看 Shield UI Grid 小部件提供的 this export sample。
这是通过像这样扩展配置来完成的:
...
exportOptions: {
proxy: "/filesaver/save",
pdf: {
fileName: "shieldui-export",
author: "John Smith",
dataSource: {
data: gridData
},
readDataSource: true,
header: {
cells: [
{ field: "id", title: "ID", width: 50 },
{ field: "name", title: "Person Name", width: 100 },
{ field: "company", title: "Company Name", width: 100 },
{ field: "email", title: "Email Address" }
]
}
}
}
...
这个例子很好用。
<button onclick="genPDF()">Generate PDF</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<script>
function genPDF() {
var doc = new jsPDF();
doc.text(20, 20, 'Hello world!');
doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.');
doc.addPage();
doc.text(20, 20, 'Do you like that?');
doc.save('Test.pdf');
}
</script>
不满意 html2canvas 的渲染以及缺乏现代 CSS3/JS 和打印 pdfMake 过时版本的 WebKit 的特定 CSS 支持...
这是一个理论上的解决方案,它是无头的,可以忠实地呈现页面,支持分页符、页边距、不同的页面大小并且可以自动化。您甚至可以将 WebGl 呈现为 PDF。
Chrome 有一个 devtools 协议......它有一个 printtoPDF 功能 摘录:https://gitlab.com/-/snippets/new 官方 20k-SLOC 规范:https://github.com/ChromeDevTools/devtools-protocol/blob/主/json/browser_protocol.json
摘录:https://gitlab.com/-/snippets/new
官方 20k-SLOC 规范:https://github.com/ChromeDevTools/devtools-protocol/blob/master/json/browser_protocol.json
您可以使用 node 和 https://github.com/GoogleChrome/chrome-launcher 来运行 chrome headless ... 等待它呈现。
利润
您将在 chrome_devtools 协议上运行的 printToPDF 命令:
printToPDF({
printBackground: false,
pageWidth: 8.5,
pageHeight: 11,
transferMode: "ReturnAsStream" // or ReturnAsBase64
})
要将 div 捕获为 PDF,您可以使用 https://grabz.it 解决方案。它有一个简单灵活的 JavaScript API,允许您捕获单个 HTML 元素的内容,例如 div 或 span
为了实现它,您首先需要获得 app key and secret 和 download(免费)SDK。
现在举个例子。
假设您有 HTML:
<div id="features">
<h4>Acme Camera</h4>
<label>Price</label>$399<br />
<label>Rating</label>4.5 out of 5
</div>
<p>Cras ut velit sed purus porttitor aliquam. Nulla tristique magna ac libero tempor, ac vestibulum felisvulput ate. Nam ut velit eget
risus porttitor tristique at ac diam. Sed nisi risus, rutrum a metus suscipit, euismod tristique nulla. Etiam venenatis rutrum risus at
blandit. In hac habitasse platea dictumst. Suspendisse potenti. Phasellus eget vehicula felis.</p>
要捕获功能 ID 下的内容,您需要:
//add the sdk
<script type="text/javascript" src="grabzit.min.js"></script>
<script type="text/javascript">
//login with your key and secret.
GrabzIt("KEY", "SECRET").ConvertURL("http://www.example.com/my-page.html",
{"target": "#features", "format": "pdf"}).Create();
</script>
请注意target: #feature
。 #feature
是您的 CSS 选择器,就像在前面的示例中一样。现在,当页面加载时,现在将在与 script 标签相同的位置创建图像屏幕截图,其中将包含 features div 的所有内容,仅此而已。
您可以对 div-screenshot 机制进行其他配置和自定义,请查看here
2022 答案:
从 HTML 元素生成 PDF 并提示保存文件:
import { jsPDF } from "jsPDF"
function generatePDF() {
const doc = new jsPDF({ unit: 'pt' }) // create jsPDF object
const pdfElement = document.getElementById('pdf') // HTML element to be converted to PDF
doc.html(pdfElement, {
callback: (pdf) => {
pdf.save('MyPdfFile.pdf')
},
margin: 32, // optional: page margin
// optional: other HTMLOptions
})
}
<button onclick="generatePDF()">Save PDF</button>
...
要在不打印的情况下预览 PDF:
doc.html(pdfElement, {
callback: (pdf) => {
const myPdfData = pdf.output('datauri')
}
})
<embed type="application/pdf" src={myPdfData} />
...
更多 HTML 选项:
https://github.com/parallax/jsPDF/blob/master/types/index.d.ts
任何人都试试这个
(function () {
var
form = $('.form'),
cache_width = form.width(),
a4 = [595.28, 841.89]; // for a4 size paper width and height
$('#create_pdf').on('click', function () {
$('body').scrollTop(0);
createPDF();
});
//create pdf
function createPDF() {
getCanvas().then(function (canvas) {
var
img = canvas.toDataURL("image/png"),
doc = new jsPDF({
unit: 'px',
format: 'a4'
});
doc.addImage(img, 'JPEG', 20, 20);
doc.save('Bhavdip-html-to-pdf.pdf');
form.width(cache_width);
});
}
// create canvas object
function getCanvas() {
form.width((a4[0] * 1.33333) - 80).css('max-width', 'none');
return html2canvas(form, {
imageTimeout: 2000,
removeContainer: true
});
}
}());
<div>
,它可能是数百个之一 - 所以他必须标记所有 不需要的 DOM 元素?doc.fromHTML
不再受支持