我正在尝试将 XML 数据从网页转换为 PDF 文件,我希望能够完全在 JavaScript 中完成此操作。我需要能够绘制文本、图像和简单的形状。我希望能够完全在浏览器中完成此操作。
我刚刚编写了一个名为 jsPDF 的库,它仅使用 Javascript 生成 PDF。它还很年轻,我很快就会添加功能和错误修复。还获得了一些在不支持数据 URI 的浏览器中解决方法的想法。它是根据麻省理工学院的自由许可证获得许可的。
我在开始写这个问题之前就遇到了这个问题,我想我会回来让你知道:)
创建“Hello World”PDF 文件的示例。
// Default export is a4 paper, portrait, using milimeters for units
var doc = new jsPDF()
doc.text('Hello world!', 10, 10)
doc.save('a4.pdf')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.debug.js"></script>
另一个值得一提的 javascript 库是 pdfmake。
浏览器支持似乎没有jsPDF那么强,似乎也没有形状选项,但格式化文本的选项比jsPDF中当前可用的选项更高级。
我维护 PDFKit,它也为 pdfmake 提供支持(这里已经提到过)。它可以在 Node 和浏览器中运行,并且支持许多其他库不支持的功能:
查看 http://pdfkit.org/ 获取完整教程,亲自了解 PDFKit 的功能。有关可以生成哪些类型的文档的示例,请查看使用 PDFKit 本身从一些 Markdown 文件生成的 PDF 文档:http://pdfkit.org/docs/guide.pdf. 您还可以在此处的浏览器中以交互方式尝试:
http://pdfkit.org/demo/browser.html它非常适合在 React 中创建 PDF 文件,甚至可以让用户从客户端本身下载它们,而不需要服务器!
这是 React-PDF 的一个小示例片段,用于创建 2 部分 PDF 文件
import React from 'react';
import { Page, Text, View, Document, StyleSheet } from '@react-pdf/renderer';
// Create styles
const styles = StyleSheet.create({
page: {
flexDirection: 'row',
backgroundColor: '#E4E4E4'
},
section: {
margin: 10,
padding: 10,
flexGrow: 1
}
});
// Create Document Component
const MyDocument = () => (
<Document>
<Page size="A4" style={styles.page}>
<View style={styles.section}>
<Text>Section #1</Text>
</View>
<View style={styles.section}>
<Text>Section #2</Text>
</View>
</Page>
</Document>
);
这将生成一个单页 PDF 文档。里面有两个不同的块,每个块都呈现不同的文本。这些不是您可以使用的唯一有效原语。您可以参考组件
或示例部分了解更多信息。
。
它生成的是带有
更容易使用。 (我喜欢它)
这可能会有所帮助。 (JSPdf 无法完成我们想要的大多数节省时间的事情,编辑现有模板。)
看看代码多漂亮
<script type="text/javascript">
async function downloadPdf() {
const url = './print-templates/pquot-template.pdf';
const existingPdfBytes = await fetch(url).then(res => res.arrayBuffer());
// Getting the document
const pdfDoc = await PDFLib.PDFDocument.load(existingPdfBytes);
// Getting the first page
const pages = pdfDoc.getPages();
const firstPage = pages[0];
// Customer name
firstPage.drawText('Customer name is here with more text (GAR004) quick brown customerm jumps over lazy dog.', {
x: 10.5*9,
y: 76.6*9,
size: 10,
maxWidth: 28*9, // Wrap text with one line. WOW :O
lineHeight: 1.5*9
});
// Currency short code
firstPage.drawText('LKR', {
x: 10.5*9,
y: 73.5*9,
size: 10
});
var itemName = 'Here is the item name with some really really long text and quick brown fox jumps over lazy dog. long text and quick brown fox jumps over lazy dog:)';
// Item name
firstPage.drawText(itemName, {
x: 5*9,
y: 67*9,
size: 10,
maxWidth: 31*9,
lineHeight: 2*9
});
const pdfDataUri = await pdfDoc.saveAsBase64({ dataUri: true });
document.getElementById('pdf').src = pdfDataUri;
}
</script>