PDF学习三 PDF文件逻辑结构

本文转自: https://blog.csdn.net/u012632138/article/details/80648760

说明:

要解析一个PDF文件,首先要掌握PDF的物理结构,这是第一步。但是这个仅仅只是基础,更重要的是对PDF逻辑结构的解析。PDF的逻辑大体上是一个树状结构,根节点是catalog字典,通过这里去解析页、目录、链接信息等等。

PDF reference 1.7.pdf 中3.6节。

目标:

掌握PDF树型结构,掌握从Root到Page Content解析流程。

Catalog根节点

Catalog是整个PDF逻辑结构的根节点,是通过trailer的Root字段定位,相当重要,因为这里是PDF文件物理结构和逻辑结构的连接点。Catalog字典包含的信息非常多,这里仅列了Pages做个说明。

完整的可查看 PDF reference1.7.pdf Page 137。

以下是Catalog 字典

3 0 obj                % 根据Root中指定的间接引用对象号找到Catalog字典
<<
/Type /Catalog    % 指定类型是Catalog,区分大小写 
/Pages 1 0 R      % 指向页面树的跟节点
>>

endobj                % 对象结束关键字

Page Tree 根节点

1 0 obj             % 根据Catalog字典中Pages指定的间接引用对象号找到Pages字典
<<
/Type /Pages
/Kids [2 0 R]    % 该Page Tree节点下的子节点,可以是Page字典,也可以是其他Page Tree节点           
/Count 1          % 该文档的页面数,1说明文档只有1页。
>>

endobj

Page 字典

2 0 obj                                   % Page 字典
<<
/Type /Page 
/Parent 1 0 R                         % parent page tree node
/MediaBox [0 0 612 792]       % page size (612x792 points)
/Contents 4 0 R                     % content stream
/Resources <<                       % resource dictionary
/Font <<                                 % font list
/Font1 5 0 R>>
 >> >>

endobj

Contents字典

4 0 obj                                   % the page content stream
<<
/Length 0                              % should be byte length of the stream data. 
                                             % We use 0 here for convenience.
>> stream

% Text example: draw "Hello World!" text

BT                                        % begin text object
/Font1 10 Tf                         % set font to /Font1, font size to 10 points
100 700 TD                         % move text position to 100,700
(Hello World!) Tj                  % output the text
ET                                        % end text object

endstream
endobj

Resources字典

这个例子中包含的是font字典

5 0 obj                                 % a font dictionary. 
                                            % This is a base-14 font, so only a few data is required.
<<
/Type /Font
/Subtype /Type1
/BaseFont /Helvetica
>>
endobj

页面继承

看下图,例如Rotate属性可以从page 父节点中继承。

Caption

 

Name Dictionary

PDF文件中的一些对象类型可以被名称引用而不是被对象引用。名称和对象之间的对应是通过文档的名称字典(PDF1.2)建立的,通过Names选项定位在文档目录册中(参看3.6.1部分,“文档目录册”)。在这个字典中的每个选项指派一个名称树结构的根节点(参看3.8.5部分,“名称树”)。

后记:

Catalog中还有许多其他条目,例如:Outline、OpenAction、PageLabels、OpenAction、AA、AcroForm,大家对哪个感兴趣,可留言给我。

问题汇总:

1)Q:Catalog指向的Pages root节点中的Count数是表示该文档的所有页面吗?

A:是的,是该文档的页面总数。PDF中说明:(Required) The number of leaf nodes (page objects) that are descendants of this node within the page tree.

2)Q:Points单位

1 Points = 1/72 inch

屏幕 1 inch = 96 pixel

PDF中Points 坐标转换为屏幕pixel。 例如页面宽为w:w*96/72 得出在屏幕上显示的值。

3)Q:PDF单位能换吗?例如可以将Points换为inch吗?

A:PDF单位只能是Point,1/72 inch。在Page 对象中有UserUnit,可以设置用户空间单位,默认是1。可以设置为2,相当于整个坐标系放大2倍,例如 10*10的矩形框,在UserUnit 为2的里面相当于20*20的矩形框。

/UserUnit 2