当前位置: 代码迷 >> 综合 >> PDFBox 数据组织思路
  详细解决方案

PDFBox 数据组织思路

热度:84   发布时间:2024-02-29 10:02:23.0

一句话: 数据与操作分离
类只负责操作字典,来减少类中所包含的主要起POJO作用的成员。
我想了想,可能这样进行输出的时候,数据组织的规则可以避免和类的结构进行耦合,只不过由于完全通过字典进行数据组织,字典本身的结构是另一种没有被类的层级关系描述的规则
另外一篇 手记 提到了这几个类的关系。皆位于 org.apache.pdfbox.pdmodel 中。

感兴趣可以继续往下看。

几个典型类的数据组织方式

    • PDDocument
    • PDDocumentCatalog
    • PDPageTree
    • PDPage

PDDocument

通过初始化其成员 COSDocument document,
及该成员内部成员 COSDictionary trailer
以字典树(value 包含一个 字典) 形式组织数据。

    public PDDocument() {
    this(MemoryUsageSetting.setupMainMemoryOnly());}public PDDocument(MemoryUsageSetting memUsageSetting) {
    // Scratch 草稿ScratchFile scratchFile = null;try {
    scratchFile = new ScratchFile(memUsageSetting);}catch (IOException ioe) {
    LOG.warn("Error initializing scratch file: " + ioe.getMessage() +". Fall back to main memory usage only.");try{
    scratchFile = new ScratchFile(MemoryUsageSetting.setupMainMemoryOnly());}catch (IOException ioe2) {
    }}document = new COSDocument(scratchFile);pdfSource = null;// First we need a trailerCOSDictionary trailer = new COSDictionary();document.setTrailer(trailer);// Next we need the root dictionary.COSDictionary rootDictionary = new COSDictionary();trailer.setItem(COSName.ROOT, rootDictionary);rootDictionary.setItem(COSName.TYPE, COSName.CATALOG);rootDictionary.setItem(COSName.VERSION, COSName.getPDFName("1.4"));// next we need the pages tree structureCOSDictionary pages = new COSDictionary();rootDictionary.setItem(COSName.PAGES, pages);pages.setItem(COSName.TYPE, COSName.PAGES);COSArray kidsArray = new COSArray();pages.setItem(COSName.KIDS, kidsArray);pages.setItem(COSName.COUNT, COSInteger.ZERO);
setTrailer()
setItem(COSName.ROOT, rootDictionary)
setItem(COSName.PAGES, pages)
PDDocument
COSDocument trailer
COSDictionary rootDictionary
pages

PDDocumentCatalog

此类的构造调用时机在PDDocument.getPDDocumentCatalog()中
1).如果由PDDocument对象构建,那么将其储存在成员对象PDDocument document中,作为上级对象储存。并创建COSDictionary对象向上注册给document.trailer作为root
2).如果传过来PDDocument documentCOSDictionary root,那就不重建root
代码如下:

    public PDDocumentCatalog(PDDocument doc) {
    document = doc;root = new COSDictionary();root.setItem(COSName.TYPE, COSName.CATALOG);document.getDocument().getTrailer().setItem(COSName.ROOT, root);}public PDDocumentCatalog(PDDocument doc, COSDictionary rootDictionary) {
    document = doc;root = rootDictionary;}

PDDocumentCatalog其实就是PDDocument中的非成员变量COSDictionary root的数据操作类。

PDPageTree

以此类推,PDPageTree实际上是PDDocument中的非成员变量COSDictionary pages的数据操作类。从其构造函数可以发现一样的构造逻辑。

PDPage

PDPage则是拥有成员COSDictionary page,装载单个页面所需要的全部东西。
当然,还是秉持一个规则。类 操作 字典。