PDFKit Node.js 测量单位

PDFKit Node.js measurement unit

PDFKit (Node.js) 中使用的度量单位是什么?例如我们使用:

doc.text(20, 20, 'Message')

20(x)20(x) 代表什么?是厘米、毫米还是英寸?我可以将其更改为任何熟悉的格式,例如 cmmminch 吗?

有什么想法吗?

作为大多数 PDF 生成器 (如果没有的话),PDFKit 使用 points too as stated in the official documentation under the Adding pages 部分作为 PDF 点:

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.

...

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.

此单位不仅适用于指定布局尺寸时,而且适用于使用任何类型的编号单位修改生成的 PDF 时。 (例如绘制文字、图片、矢量图等)


PDF is derived from PostScript, it uses internally the same graphics model too including the same basic measurement unit as PostScript, which is points(72 points == 1 inch)。此测量单位是 设备独立的使用和声明尺寸的方式


您不能更改 PDFKit 的测量单位。 为了使用其他单位而不是分数,您必须自己计算单位并 乘以一个系数根据积分。由于您 未绑定到整数点 ,因此在指定点 时也可以使用 浮点数(例如:100.15)。


示例:

如果您使用 A4 大小的页面(即 8.27 × 11.69 inches210 × 297 mm),其尺寸将四舍五入为 595 × 842 points (简称pt):

  • 1pt~0.35mm,或 ~0.04cm
  • 10pt~3.53mm,或 ~0.35cm
  • 100pt~35.28mm,或 ~3.53cm
  • 148.75pt(四分之一页宽)为 ~52.48mm~5.25cm
  • 297.5pt(半页宽)为~104.95mm~10.50cm

如果您需要像素,您的计算也必须基于特定的 DPI,因此 A4[=98= 的像素尺寸] 大小的页面:

  • 72 DPI595 x 842px
  • 96 DPI794 x 1123px
  • 150 DPI1240 x 1754px
  • 300 DPI2480 x 3508px

对于初学者,这是一个简单的脚本,列出了转换为您提到的点后的基本单位及其值:

function mmToPt (mm) {
  return mm * 2.83465;
}

function cmToPt (cm) {
  return cm * 28.3465;
}

function inchToPt (inch) {
  return inch * 72;
}

const units = [
  1,
  2,
  3,
  5,
  10,
  15,
  20,
  25,
  50,
  100,
  150,
  250,
  500,
  1000
];

function convert (unit) {
  let name;
  let converter;
  
  switch (unit) {
    case 'mm':
      name = 'millimeters';
      converter = mmToPt;
      break;
    
    case 'cm':
      name = 'centimeters';
      converter = cmToPt;
      break;
      
    case 'inch':
      name = 'inches';
      converter = inchToPt;
      break;
  }
  
  console.log(`Convert ${name} to points:`);
  
  units.forEach(u => {
    let converted = converter(u).toFixed(2);
    
    // get rid of unneeded .00 decimals
    if (+converted === parseInt(converted, 10)) {
      converted = +converted;
    }
    
    console.log(`${u}${unit} is ${converted}pt, so in doc.text(${converted}, ${converted}, 'Message')`);
  });
  
  console.log('--------------------------------------------');
}

convert('mm');
convert('cm');
convert('inch');

You can find a table of paper sizes with corresponding dimensions in points. 此 table 适用于 PDFKit 和大多数 (如果没有的话) 的 PDF 生成器。