perl PDF text coordinates

时间:2015-07-31 20:28:40

标签: perl pdf

this a simple hello world test script in perl to generate a PDF file :

#!/usr/bin/perl

use PDF::API2;

# Create a blank PDF file
$pdf = PDF::API2->new();

# Add a blank page
$page = $pdf->page();

# Set the page size
$page->mediabox('A4');

# Add a built-in font to the PDF
$font = $pdf->corefont('Helvetica-Bold');

# Add some text to the page
$text = $page->text();
$text->font($font, 20);
$text->translate(72, 28); # 1inch, 1cm
$text->text('Hello World!');

# Save the PDF
$pdf->saveas('test.pdf');

I was expecting the bottom of my text to be 1cm above the page bottom but it's not (on the other hand, the x position is correctly at 1 inch from the left of the page).

Measuring on the printed page shows that 1cm is at the center of the text (more or less). Does this mean the y-positioning of an object is from its vertical middle ?

Thanks

1 个答案:

答案 0 :(得分:2)

这是从输出PDF中复制和粘贴的几个关键对象,一旦解压缩:

Page对象:

5 0 obj
<< /Type /Page /Contents [ 7 0 R ] /MediaBox [ 0 0 595 842 ] /Parent 2 0 R
   /Resources << /Font << /HeBoCBA~1438376482 6 0 R >> /ProcSet
   [/PDF /Text /ImageB /ImageC /ImageI ] >> >>
endobj

页面内容:

7 0 obj
<< /Length 77 >>
stream
BT  /HeBoCBA~1438376482 20 Tf 1 0 0 1 72 28 Tm [ (Hello World!) ] TJ  ET
endstream
endobj

媒体框为[0 0 595 842],即A4。

说明1 0 0 1 72 28 Tm(设置文字矩阵)将Tx设为72,将Ty设为28。

所以看一下PDF,似乎正确地将页面大小设置为A4并将文本从其基线而不是其中心定位。

更新的 这是一个屏幕截图,显示Adobe Reader中PDF的外观Hello World!,使用300%的缩放比例的测量工具。

enter image description here