我正在寻找一个库,可以在按钮的点击事件后将我的网页转换为PDF文件。我尝试使用jspdf
,但它打印出来没有CSS,我如何使用JavaScript/jQuery
进行转换并保留我的CSS?或者选择另一个CSS样式?
我正在寻找一个库,可以在按钮的点击事件后将我的网页转换为PDF文件。我尝试使用jspdf
,但它打印出来没有CSS,我如何使用JavaScript/jQuery
进行转换并保留我的CSS?或者选择另一个CSS样式?
现在有一个新的jQuery + 云解决方案,可以将任何HTML页面及其CSS(包括打印媒体规则)呈现为PDF。该解决方案设置为打印网页的任何区域,您只需告诉格式化程序要打印哪个容器元素,库就会完成其余工作。您得到的是可嵌入的PDF文档,或者后端将返回可下载的PDF。
以下是您的库(GitHub):
https://github.com/Xportability/css-to-pdf
以下是您的示例:
http://jsfiddle.net/kstubs/jrtM5/
以下是一个工作演示:
http://xep.cloudformatter.com/doc/
目前还没有使用说明,但跟随示例(查看源代码)应该很容易理解(查找“Print It”按钮),这里大致列出了Format方法理解的附加选项/参数。
options
{
pageWidth: "8.5in",
pageHeight: "11in",
pageMargin: ".25in",
pageMarginTop: "1in",
pageMarginRight: "1in",
pageMarginBottom: "1in",
pageMarginLeft: "1in",
render: ("none"|"newwin<default>"|embed"|"download<default IE>"),
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'
]
希望这能帮到你!
https://www.github.com
网站的PDF:<a href="https://dhtml2pdf.herokuapp.com/api.php?url=https://www.github.com&result_type=show" target="_blank">Show PDF</a>
如何使用它来下载PDF的示例:
<a href="https://dhtml2pdf.herokuapp.com/api.php?url=https://www.github.com&result_type=download&file_name=my_pdf">Download PDF</a>
通过这个解决方案,您甚至不需要使用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'));
});
尝试使用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
*你也可以指定尺寸。Phantom版本 ^4.0.3,Node版本 v6.5.0。https://www.npmjs.com/package/htmlto