开启PDFKit之旅吧

Getting Started with PDFKit

开启PDFKit之旅吧

Installation

安装

使用npm包管理器安装。只需在安装npm后输入以下命令:
Installation uses the npm package manager. Just type the following command after installing npm.

npm install pdfkit

创建文档
Creating a document
创建PDFKit文档很简单。只需要在JavaScript代码源文件中添加pdfkit模块,并创建PDFDocument类的实例。
Creating a PDFKit document is quite simple. Just require the pdfkit module in your JavaScript source file and create an instance of the PDFDocument class.

const PDFDocument = require('pdfkit');
const doc = new PDFDocument;

PDFDocument实例是可读的Node流。他们不会自动保存到任何地方,但你可以调用管道方法将PDF文档输出到其他可写的Node流,以实现写文件。当你操作完文档,调用结束方法的文档以完成写入。以下例子展示了怎样输出到文件或HTTP响应。
PDFDocument instances are readable Node streams. They don’t get saved anywhere automatically, but you can call the pipe method to send the output of the PDF document to another writable Node stream as it is being written. When you’re done with your document, call the end method to finalize it. Here is an example showing how to pipe to a file or an HTTP response.

doc.pipe(fs.createWriteStream('/path/to/file.pdf')); // write to PDF

doc.pipe(res); // HTTP response

// add stuff to PDF here using methods described below...

// finalize the PDF and end the stream
doc.end();

PDFkit0.5以下版本的写入和输出方法现在以不推荐使用。
The write and output methods found in PDFKit before version 0.5 are now deprecated.
在浏览器中使用PDFKit
Using PDFKit in the browser
PDFkit可以像Node一样在浏览器中在使用!在浏览器中使用有两种方式。第一种:使用模块绑定,比如Browserfy或Webpack。第二种 :创建独立的pdfkit角本,以下再做说明。
PDFKit can be used in the browser as well as in Node! There are two ways to use PDFKit in the browser. The first is to create an app using an module bundler like Browserify or Webpack. The second is to create a standalone pdfkit script as explained here.
在浏览器中使用PDFKit与在Node下使用完成一样,除非你想将PDF输出到特定浏览器,比如Blob。Blobs可用以生成URL以请允许在浏览器中直接显示PDF——通过ifame或将PDF上传到服务器,或在用户浏览器中触发下载。
Using PDFKit in the browser is exactly the same as using it in Node, except you’ll want to pipe the output to a destination supported in the browser, such as a Blob. Blobs can be used to generate a URL to allow display of generated PDFs directly in the browser via an iframe, or they can be used to upload the PDF to a server, or trigger a download in the user’s browser.
为了在PDFDocument中获取Blob,你可以pipe为blob流(它是一个可以生成从Node类型的流转为Blob模块)。以下例子使用Browerify加载PDFKit和blob流,但如你不是使用Browserify,你可以使用任何你喜欢的工具加载,比如script tags。
To get a Blob from a PDFDocument, you should pipe it to a blob-stream, which is a module that generates a Blob from any Node-style stream. The following example uses Browserify to load PDFKit and blob-stream, but if you’re not using Browserify, you can load them in whatever way you’d like (e.g. script tags).

// require dependencies
const PDFDocument = require('pdfkit');
const blobStream  = require('blob-stream');

// create a document the same way as above
const doc = new PDFDocument;

// pipe the document to a blob
const stream = doc.pipe(blobStream());

// add your content to the document here, as usual

// get a blob when you're done
doc.end();
stream.on('finish', function() {
  // get a blob you can do whatever you like with
  const blob = stream.toBlob('application/pdf');

  // or get a blob URL for display in the browser
  const url = stream.toBlobURL('application/pdf');
  iframe.src = url;
});

你可以在这里看到PDFKit在浏览器中的交互。
You can see an interactive in-browser demo of PDFKit here.
注意:为了在Browserfay工程中使用PDFkit,你需要使用bpm安装brfs模块——它是可以加载字体数据到包中。以下是PDFKit的package.js文件中的依赖列表,这些不是Node默认安装的。如果你忘了安装,Browserify将会输出error消息。
Note that in order to Browserify a project using PDFKit, you need to install the brfs module with npm, which is used to load built-in font data into the package. It is listed as a devDependencies in PDFKit’s package.json, so it isn’t installed by default for Node users. If you forget to install it, Browserify will print an error message.

添加页
Adding pages
PDFKit文档的第一页是在创建文档时自动添加的(除非你将autoFirstPage设置为false)。随后的页只有由你添加。很幸运,这很简单。
The first page of a PDFKit document is added for you automatically when you create the document unless you provide autoFirstPage: false. Subsequent pages must be added by you. Luckily, it is quite simple!

doc.addPage()

为了在每次添加页时都添加相同的内容,你可以在添加面的事件中添加代码。
To add some content every time a page is created, either by calling addPage() or automatically, you can use the pageAdded event.

doc.on('pageAdded', () => doc.text("Page Title"));

当然你也可以为页设置参数,比如大小和方向(横向、纵向)。
You can also set some options for the page, such as its size and orientation.
布局属性可以是portrait或landscape。大小属性可以是数组width,height,或是以字符串指定的以定义的大小。预定义的纸张大小下面会列出。默认是letter。
The layout property can be either portrait (the default) or landscape. The size property can be either an array specifying [width, height] in PDF points (72 per inch), or a string specifying a predefined size. A list of the predefined paper sizes can be seen here. The default is letter.

传递页面属性对象到PDFDocument构造方法将会设置页面大小和布局(针对文档中的每页),单独的选项将会addPage方法。
Passing a page options object to the PDFDocument constructor will set the default paper size and layout for every page in the document, which is then overridden by individual options passed to the addPage method.
设置页页边距有两种方式。第一种是:设置页边距属性为数值——这将会对所有边生效。第二种是:设置页边距属性为对象(包含top,bottom,left,right值)。默认在所有边都是1英寸(72点)页边距。
You can set the page margins in two ways. The first is by setting the margin property (singular) to a number, which applies that margin to all edges. The other way is to set the margins property (plural) to an object with top, bottom, left, and right values. The default is a 1 inch (72 point) margin on all sides.
例如:
For example:

// Add a 50 point margin on all sides
doc.addPage({
  margin: 50});


// Add different margins on each side
doc.addPage({
  margins: {
    top: 50,
    bottom: 50,
    left: 72,
    right: 72
  }
});

切换到前一页
Switching to previous pages
PDFKit一般是在新的页创建时将页面数据刷到输出文件中,这样的机制是为了确保不能跳回和添加内容到前一页。这在一般情况下不是问题,但是有些情形下添加内容到已经创建的所有页或者是部分页是有用的。比如添加页码,或在剩下的文档被创建之后才能填入的消息。
PDFKit normally flushes pages to the output file immediately when a new page is created, making it impossible to jump back and add content to previous pages. This is normally not an issue, but in some circumstances it can be useful to add content to pages after the whole document, or a part of the document, has been created already. Examples include adding page numbers, or filling in other parts of information you don’t have until the rest of the document has been created.

PDFKit v0.70中有缓存页选项,之后的版本允许你在页面刷入外部文件后仍可自己操作,而不是让PDFKit为你处理。为了使用这个功能,只需要传递bufferPages等true到PDFDocument构造方法。然后,你可以调用doc.switchToPage(pageNumber)切换到前一页(页页从0开始)
PDFKit has a bufferPages option in versions v0.7.0 and later that allows you to control when pages are flushed to the output file yourself rather than letting PDFKit handle that for you. To use it, just pass bufferPages: true as an option to the PDFDocument constructor. Then, you can call doc.switchToPage(pageNumber) to switch to a previous page (page numbers start at 0).

当你准备刷入缓存页到文件时,调用flushPages。这个方法是自动调用doc.end(),所以如果你只是想缓存所有文档中的页,你不需要调用它。最后有一个bufferedPageRange方法,它返回当前缓存的部分页。以下是小示例如何添加页码到文档。
When you’re ready to flush the buffered pages to the output file, call flushPages. This method is automatically called by doc.end(), so if you just want to buffer all pages in the document, you never need to call it. Finally, there is a bufferedPageRange method, which returns the range of pages that are currently buffered. Here is a small example that shows how you might add page numbers to a document.

// create a document, and enable bufferPages mode
let i;
let end;
const doc = new PDFDocument({
  bufferPages: true});

// add some content...
doc.addPage();
// ...
doc.addPage();

// see the range of buffered pages
const range = doc.bufferedPageRange(); // => { start: 0, count: 2 }

for (i = range.start, end = range.start + range.count, range.start <= end; i < end; i++;) {
  doc.switchToPage(i);
  doc.text(`Page ${i + 1} of ${range.count}`);
}

// manually flush pages that have been buffered
doc.flushPages();

// or, if you are at the end of the document anyway,
// doc.end() will call it for you automatically.
doc.end();

设置默认字体
Setting default font
默认字体是’Helvetica’。传递字体选项配置:
The default font is ‘Helvetica’. It can be configured by passing font option

// use Courier font by default
const doc = new PDFDocument({font: 'Courier'});

设置文档元数据
Setting document metadata
PDF文档设置与其相关的多种元数据,比如标题,作者。你可以添加这些信息到文档doc.info对象,或在创建的时候传入。
PDF documents can have various metadata associated with them, such as the title, or author of the document. You can add that information by adding it to the doc.info object, or by passing an info object into the document at creation time.
以下是所以可以添加的元数据。根据PDF规范,每个属性的首字母是大写的。
Here is a list of all of the properties you can add to the document metadata. According to the PDF spec, each property must have its first letter capitalized.

  • Title - the title of the document Author - the name of the author
  • Subject - the subject of the document Keywords keywords associated with the document
  • CreationDate - the date the document was created
    (added automatically by PDFKit)
  • ModDate - the date the document was
    last modified Encryption and Access Privileges

PDF规范请允许你加密PDF文件——在打开PDF文件时需要密码,或者设置PDF哪些用户请允许我打开文件。PDFKit实现了PDF v1.3安全标准,以及1.4、1.7,及1.7的扩展3。
PDF specification allow you to encrypt the PDF file and require a password when opening the file, and/or set permissions of what users can do with the PDF file. PDFKit implements standard security handler in PDF version 1.3 (40-bit RC4), version 1.4 (128-bit RC4), PDF version 1.7 (128-bit AES), and PDF version 1.7 ExtensionLevel 3 (256-bit AES).
为了启用加密,需要在创建PDFDocument对象时传入用户名密码。当有密码时PDF文件将会加密,用户打开文件时将会被要求输入密码。
To enable encryption, provide a user password when creating the PDFDocument in options object. The PDF file will be encrypted when a user password is provided, and users will be prompted to enter the password to decrypt the file when opening it.

  • userPassword - the user password (string value) To set access
    privileges for the PDF file, you need to provide an owner password
    and permission settings in the option object when creating
    PDFDocument. By default, all operations are disallowed. You need to
    explicitly allow certain operations.
  • ownerPassword - the owner password (string value) permissions - the
    object specifying PDF file permissions Following settings are allowed
    in permissions object:
  • printing - whether printing is allowed. Specify “lowResolution” to
    allow degraded printing, or “highResolution” to allow printing with
    high resolution modifying - whether modifying the file is allowed.
    Specify true to allow modifying document content
  • copying - whether copying text or graphics is allowed. Specify true
    to allow copying
  • annotating - whether annotating, form filling is allowed. Specify
    true to allow annotating and form filling
  • fillingForms - whether form filling and signing is allowed. Specify
    true to allow filling in form fields and signing
  • contentAccessibility - whether copying text for accessibility is
    allowed. Specify true to allow copying for accessibility
    documentAssembly - whether assembling document is allowed. Specify
    true to allow document assembly You can specify either user password,
    owner password or both passwords. Behavior differs according to
    passwords you provides:
    当用户密码提供时,用户有密码就可以解密文件,并对文档有所有访问权限。
    When only user password is provided, users with user password are able to decrypt the file and have full access to the document.
    当所有者密码提供时,用户可以解密文件,打开文件时不需要密码,但访问是受限的。有所有者密码的用户才有对整个文档的权限。
    When only owner password is provided, users are able to decrypt and open the document without providing any password, but the access is limited to those operations explicitly permitted. Users with owner password have full access to the document.
    当两种密码都提供时,有用户密码的可以解密文件,但只有权限设置中的访问一允许的。有所有者密码的对文档有所有访问权限。注意:PDF文件自身不能修改访问权限。当文件加密时,PDF浏览应用程序有访问文档内容的所有权限,浏览应用程序会尊守权限设置。
    When both passwords are provided, users with user password are able to decrypt the file but only have limited access to the file according to permission settings. Users with owner password have full access to the document.
    Note that PDF file itself cannot enforce access privileges. When file is decrypted, PDF viewer applications have full access to the file content, and it is up to viewer applications to respect permission settings.
    为了选择加密方法,你需要指定PDF的版本。PDFKit会根据版本选择合适的加密方法。
    To choose encryption method, you need to specify PDF version. PDFKit will choose best encryption method available in the PDF version you specified.
  • pdfVersion - a string value specifying PDF file version Available
    options includes:

1.3 - PDF version 1.3 (default), 40-bit RC4 is used
1.4 - PDF version 1.4, 128-bit RC4 is used
1.5 - PDF version 1.5, 128-bit RC4 is used
1.6 - PDF version 1.6, 128-bit AES is used
1.7 - PDF version 1.7, 128-bit AES is used
1.7ext3 - PDF version 1.7 ExtensionLevel 3, 256-bit AES is used

When using PDF version 1.7 ExtensionLevel 3, password is truncated to 127 bytes of its UTF-8 representation. In older versions, password is truncated to 32 bytes, and only Latin-1 characters are allowed.
添加内容
Adding content

当创建了PDFDocument实例后,就可以添加内容到文档。查看其他章节可以学习每种类型的内容如何添加。
Once you’ve created a PDFDocument instance, you can add content to the document. Check out the other sections described in this document to learn about each type of content you can add.
这是基础!现在把视线转移到PDFKit强大的图形绘制能力去。
That’s the basics! Now let’s move on to PDFKit’s powerful vector graphics abilities.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值