如何从html网页生成pdf?

我正在寻找一个库,可以在从按钮点击事件后将我的网页转换为PDF文件。 我正在尝试jspdf ,但它打印没有CSS,我怎样才能使用JavaScript/jQuery并保留我的CSS? 还是我可以选择的另一个CSS?

有一个新的jQuery +云解决方案,可以将任何HTML页面及其CSS(包括打印媒体规则)呈现为PDF。 解决方案设置为打印网页的任何区域,您只需告诉Formatter您要打印哪个容器元素,库就完成剩下的工作。 你得到的是一个可嵌入的PDF或后端将推回PDF下载。

这是你的图书馆(GitHub):
https://github.com/Xportability/css-to-pdf

这是你的小提琴:
http://jsfiddle.net/kstubs/jrtM5/

这是一个有效的演示:
http://xep.cloudformatter.com/doc/

目前没有使用说明,但是跟随样本(视图源)应该是非常明显的(查找“打印”按钮),这里或多或少是Format方法理解的附加选项/参数。

 options { pageWidth: "8.5in", pageHeight: "11in", pageMargin: ".25in", pageMarginTop: "1in", pageMarginRight: "1in", pageMarginBottom: "1in", pageMarginLeft: "1in", render: ("none"|"newwin"|embed"|"download"), foStyle: { // puts fo style attributes on the root, ex. fontSize:14px foStyleName: 'value', ... } } 

以下是当前支持的CSS属性列表。

 [ 'lineHeight', 'alignmentBaseline', 'backgroundImage', 'backgroundPosition', 'backgroundRepeat', 'backgroundColor', 'baselineShift', 'border', 'borderWidth', 'borderColor','borderStyle', 'borderTop','borderLeft','borderRight','borderBotttom', 'borderTopWidth','borderTopStyle','borderTopColor', 'borderBottomWidth','borderBottomStyle','borderBottomColor', 'borderLeftWidth','borderLeftStyle','borderLeftColor', 'borderRightWidth','borderRightStyle','borderRightColor', 'borderCollapse', 'clear', 'color', 'display', 'direction', 'dominantBaseline', 'fill', 'float', 'fontStyle', 'fontVariant', 'fontWeight', 'fontSize', 'fontFamily', 'listStyleType', 'listStyleImage', 'letterSpacing', 'marginTop', 'marginBottom', 'marginLeft', 'marginRight','orphans', 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft', 'pageBreakAfter', 'pageBreakBefore', 'tableLayout', 'textAlign', 'textAnchor','textDecoration', 'textIndent', 'textTransform', 'verticalAlign', 'widows', 'wordSpacing', 'width' ] 

希望这可以帮助!

试试这个npm包htmlto它使用CSS样式从html创建PDF

 var htmlTo = require('htmlto') htmlTo.pdf('./public/html/report.html','./public/pdf/report.pdf',{width: 2480, height: 3508}) 

安装:

npm install -S htmlto

npm install -S phantom

*您还可以指定dimensions.phantom版本^ 4.0.3和节点版本v6.5.0 https://www.npmjs.com/package/htmlto

我创建了一个简单易用的API,它使用snappy库,基于wkhtmltopdf基于webkit的CLI,以便将HTML页面从URL转换为PDF。 这是Github回购: https : //github.com/Dellos7/dhtml2pdf

这是如何从锚标记中使用它的示例。 这将在新的浏览器选项卡中显示生成的https://www.github.com网站的PDF:

 Show PDF 

如何使用它下载PDF的示例:

 Download PDF 

使用此解决方案,您甚至无需使用javascript来生成PDF。

但如果你仍然需要使用javascript,你可以这样做:

 document.getElementById("your-button-id").addEventListener("click", function() { var link = document.createElement('a'); link.href = 'https://dhtml2pdf.herokuapp.com/api.php?url=https://www.github.com&result_type=download'; link.download = 'file.pdf'; link.dispatchEvent(new MouseEvent('click')); }); 

在回购中,我还解释了如何在Heroku中轻松克隆和部署自己的API,这样您就可以自己保留API而不依赖于外部服务。

Interesting Posts