jspdf 生成pdf文件
The Portable Document Format has been one the major innovations in the fields of desktop publishing and office automations.
可移植文档格式已成为桌面出版和办公室自动化领域的主要创新之一。
It’s widely used in web publishing too, but unfortunately very often in wrong ways – like using it to replace contents that should have been built with HTML. This causes many problems regarding usability, accessibility, SEO and so on.
它也广泛用于Web发布中,但不幸的是,它经常以错误的方式出现-例如使用它来替换本应由HTML构建的内容。 这会导致许多与可用性,可访问性,SEO等有关的问题。
However, there are some cases in which PDF files are required: when a document needs to be archived and must be used outside the web (for example an invoice) or when you need a deep control on printing.
然而,也有一些案件中,PDF文件是必需的:当一个文件需要被存档,并且必须在网络(例如发票),或者当你需要打印上了深刻的控制之外使用。
It was just the need to control printing that brought me to research a way to easily generate a PDF.
正是由于需要控制打印,才使我研究了一种轻松生成PDF的方法。
The purpose of this article is not to simply explain how a PDF can be created (there are many easy way to do this), but also to focus on the circumstances where a PDF file can solve a problem, and how a simple tool like jsPDF can help with this.
本文的目的不是简单地解释如何创建PDF(有许多简单的方法可以做到这一点),而是着眼于PDF文件可以解决问题的情况以及像jsPDF这样的简单工具的方式。可以帮助您。
Anyone who has dealt with CSS printing rules knows how difficult it is to achieve a decent level of cross-browser compatibility (take a look, for example, at the Page-break support table at Can I Use). Therefore, when I need to build something that must be printed, I always try to avoid CSS, and the simplest solution is to use PDF.
任何处理过CSS打印规则的人都知道实现良好的跨浏览器兼容性水平是多么困难(例如,看一下“我可以使用”的分页支持表 )。 因此,当我需要构建必须打印的内容时,我总是尽量避免使用CSS,最简单的解决方案是使用PDF。
I’m not talking here about the simple conversion of HTML to PDF. (I’ve tried several tools of that type, but none of them has fully satisfied me.) My goal is to have complete control over the positioning and size of elements, page breaks and so on.
我不是在这里谈论HTML到PDF的简单转换。 (我尝试过几种此类工具,但没有一个使我完全满意。)我的目标是完全控制元素的位置和大小,分页符等。
In the past I’ve often used FPDF, a PHP tool that can easily give you such controls and that can be easily expanded with many plugins.
过去我经常使用FPDF (PHP工具),它可以很容易地给你这样的控件,并且可以通过许多插件轻松地扩展。
Unfortunately, the library seems to be abandoned (its last version dates back to 2011) (Update: actually, the latest version appears to be from December 2015), but thanks to some JavaScript libraries, we now have the ability to build PDF files directly in the clients (thus making their generation faster).
不幸的是,该库似乎已被废弃(其最新版本可追溯到2011年)(更新: 实际上,最新版本似乎是从2015年12月开始的 ),但是由于有了一些JavaScript库,我们现在能够直接构建PDF文件在客户中(从而使他们的生成速度更快)。
When I started my project, some months ago, I searched for a JS library, and finally I found two candidates: jsPDF and pdfmake. pdfmake seems to be well documented and very easy to use, but since it was a beta version, I decided for jsPDF.
几个月前,当我开始我的项目时,我搜索了一个JS库,最后找到了两个候选对象: jsPDF和pdfmake 。 pdfmake似乎文档齐全并且非常易于使用,但是由于它是beta版本,所以我决定使用jsPDF。
The jsPDF documentation is fairly minimal, consisting of a single page along with some demos, and a little more information in the source file (or in its jsDoc pages), so keep in mind that using it for complex projects can be a little hard in the beginning.
jsPDF文档非常少,它由一个页面和一些演示组成 ,并且在源文件(或其jsDoc页面 )中有更多信息,因此请记住,在复杂项目中使用它可能有点困难。开始。
Anyway, jsPDF is very easy for basic PDF files generation. Take a look to a simple “Hello World” example:
无论如何,jsPDF对于基本PDF文件的生成非常容易。 看一个简单的“ Hello World”示例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Hello world</title> </head> <body> <h1>Hello world</h1> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js"></script> <script type="text/javascript"> var pdf = new jsPDF(); pdf.text(30, 30, 'Hello world!'); pdf.save('hello_world.pdf'); </script> </body> </html>This HTML page generates a one-page PDF file and saves it on your computer. First you have to link to the jsPDF library (in this case, from cdnjs.com), then a jsPDF instance is created, a line of text is added, and the result is saved as hello_world.pdf.
此HTML页面生成一页PDF文件,并将其保存在您的计算机上。 首先,您必须链接到jsPDF库(在本例中为cdnjs.com ),然后创建一个jsPDF实例,添加一行文本,并将结果保存为hello_world.pdf 。
Note that I’ve used the 1.0.272 version, and that it’s not the latest: at the time of writing this, the most recent version is the 1.1.135, but it has many issues, so I am still using the previous one.
请注意,我使用的是1.0.272版本,它不是最新版本:在撰写本文时,最新版本是1.1.135,但是它存在许多问题,因此我仍在使用上一个版本。 。
You can see how extremely simple it is to build a basic PDF file (you can find more examples at the jsPDF site).
您会看到构建基本PDF文件非常简单(可以在jsPDF站点上找到更多示例)。
Let’s try to build something harder.
让我们尝试构建更难的东西。
Some months ago, I was asked to build an application for creating some simple flyers. It was part of a larger project that dealt with some services for travel agencies, and the real flyer was partially populated by some JSON data.
几个月前,我被要求构建一个用于创建一些简单传单的应用程序。 它是一个较大的项目的一部分,该项目涉及旅行社的一些服务,真正的传单部分由一些JSON数据填充。
The flyer’s main aim was to provide a simple way to display special offers to be exposed in the travel agency shop window.
该传单的主要目的是提供一种简单的方法,以显示要在旅行社商店橱窗中展示的特惠信息。
I’ve rearranged that application for this article, removing all server-side functionality, simplifying the flyer design, getting rid of legacy browser compatibility and building a very simple UI with Bootstrap 3 and jQuery.
我已经为本文重新安排了该应用程序,删除了所有服务器端功能,简化了传单设计,摆脱了旧版浏览器的兼容性,并使用Bootstrap 3和jQuery构建了非常简单的UI。
The demo works well with Firefox and Chrome, while Explorer (or Edge) doesn’t allow you to display the preview, but only to download the generated PDF.
该演示与Firefox和Chrome兼容,而Explorer(或Edge)不允许您显示预览,而只能下载生成的PDF。
This is an example of a PDF created with the app (photo credit: Rafael Leão / Unsplash)
这是使用该应用创建的PDF的示例(图片来源: RafaelLeão/ Unsplash )
A functioning demo is available at the end of this article or directly in CodePen. Note that, since CodePen loads the result page in an iframe, the PDF preview – which is loaded in an iframe too – has some issues with Chrome and Safari that prevent the preview from being displayed. (Use Firefox if you can, or try the demo on my personal site).
本文结尾或直接在CodePen中提供了功能正常的演示。 请注意,由于CodePen将结果页面加载到iframe中,因此PDF预览(也加载到iframe中)与Chrome和Safari相比存在一些问题,无法显示预览。 (如果可以,请使用Firefox,或者在我的个人网站上尝试演示 )。
The user interface allows the user to insert some basic data (a title, an abstract and a price). Optionally, an image can be added, otherwise a grey-boxed Special Offer title is displayed.
用户界面允许用户插入一些基本数据(标题,摘要和价格)。 (可选)可以添加图像,否则显示灰色框的“ 特价商品”标题。
Other data (the agency name and its website URL and logo) are embedded in the application code.
其他数据(代理商名称及其网站URL和徽标)嵌入在应用程序代码中。
The PDF can be previewed in a iframe (except Explorer or Edge) or directly downloaded.
可在iframe(资源管理器或Edge除外)中预览PDF或直接下载PDF。
When the Update preview or the Download buttons are clicked, the PDF is generated using jsPDF and passed to the iframe as a data URI string or saved to disk, as in the above example.
单击“ 更新预览”或“ 下载”按钮时,将使用jsPDF生成PDF,并将其作为数据URI字符串传递到iframe或保存到磁盘,如上例所示。
The PDF generation first creates a new instance a jsPDF object with these options: portrait orientation (p), millimeters units (mm), ‘A4’ format.
PDF生成首先使用以下选项创建一个新的jsPDF对象实例:纵向方向( p ),毫米单位( mm ),“ A4”格式。
var pdf = new jsPDF('p', 'mm', 'a4');Images are added using the addImage function. Note that every object placed in the PDF page must be exactly positioned. You have to take care of the coordinates of each object using the units declared.
使用addImage函数添加图像。 请注意,放置在PDF页面中的每个对象都必须精确定位。 您必须使用声明的单位来照顾每个对象的坐标。
// pdf.addImage(base64_source, image format, X, Y, width, height) pdf.addImage(agency_logo.src, 'PNG', logo_sizes.centered_x, _y, logo_sizes.w, logo_sizes.h);Images must be Base64 encoded: the agency logo is embedded in the script in this format, while the image loaded by the user is encoded using the readAsDataURL method in the $('#flyer-image').change listener.
图片必须经过Base64编码:代理徽标以这种格式嵌入脚本中,而用户加载的图片则使用$('#flyer-image').change侦听器中的readAsDataURL方法进行编码。
The title is added using the textAlign function. Note that this function is not part of the jsPDF core, but, as suggested by the author in his examples, the library can be easily expanded using its API. You can find the textAlign() function at the top of flyer builder script:
使用textAlign函数添加标题。 请注意,此功能不是jsPDF核心的一部分,但是,正如作者在其示例中所建议的那样,可以使用其API轻松扩展该库。 您可以在传单生成器脚本的顶部找到textAlign()函数:
pdf.textAlign(flyer_title, {align: "center"}, 0, _y);This function calculates the X coordinate of the the text string to make it centered, and then calls the native text() method:
此函数计算文本字符串的X坐标以使其居中,然后调用本机text()方法:
pdf.text(text string, X, Y);To change text properties, you can use the setFontSize(), setFont(), setTextColor() and setFontType() methods.
要更改文本属性,可以使用setFontSize() , setFont() , setTextColor()和setFontType()方法。
To set a 20pt Times Bold red string, for example, you need to type this:
例如,要设置一个20pt Times Bold红色字符串,您需要输入以下内容:
pdf.setFontSize(20); pdf.setFont("times"); pdf.setFontType("bold"); pdf.setTextColor(255, 0, 0); pdf.text(10,10, 'This is a 20pt Times Bold red string');The Special offer grey box and the price circle use two similar methods: roundedRect() and circle(). Both of them require top-left coordinates, size values (the width and height in the first case and the radius in the second one):
特价商品灰色框和价格圆圈使用两种相似的方法: roundedRect()和circle() 。 它们都需要左上角的坐标,大小值(第一种情况下的宽度和高度,第二种情况下的半径):
pdf.roundedRect( X, Y, width, height, radius along X axis, radius along Y axis, style); pdf.circle( X, Y, radius, style);The style parameters refers to the fill and stroke properties of the object. Valid styles are: S [default] for stroke, F for fill, and DF (or FD) for fill and stroke.
style参数是指对象的填充和描边属性。 有效样式为: S [默认值]用于笔划, F用于填充,而DF (或FD )用于填充和笔划。
Fill and stroke properties must be set in advance using setFillColor and setDrawColor, which require a RGB value and setLineWidth that requires the line width value in the unit declared at inception of PDF document.
必须使用setFillColor和setDrawColor预先设置填充和描边属性,这需要RGB值,而setLineWidth需要以PDF文档开始时声明的单位的线宽值。
The complete code is available in the CodePen demo:
完整的代码可在CodePen演示中找到:
See the Pen PDF Flyer generator by SitePoint (@SitePoint) on CodePen.
请参阅CodePen上的SitePoint ( @SitePoint )的Pen PDF Flyer生成器 。
This basic example shows how it’s possible to build a very basic flyer with jsPDF.
这个基本示例说明了如何使用jsPDF构建非常基本的传单。
Its use could be easy, but the lack of a complete documentation makes every step really complicated.
它的使用可能很容易,但是缺少完整的文档使每个步骤都变得非常复杂。
I’m still looking around for other solutions, keeping my eye on others like pdfmake. But ultimately, I think the only really definitive solution can be better browser support for printing CSS rules!
我仍在寻找其他解决方案,同时关注pdfmake等其他解决方案。 但最终,我认为唯一真正的解决方案是为打印CSS规则提供更好的浏览器支持!
Have you used jsPDF or something similar? What was your experience? Let me know in the comments.
您是否使用过jsPDF或类似的东西? 你的经验是什么? 在评论中让我知道。
翻译自: https://www.sitepoint.com/generating-pdfs-from-web-pages-on-the-fly-with-jspdf/
jspdf 生成pdf文件
相关资源:js转pdf