尝试使用Apache Poi制作简单的PDF文档

Ale*_*ser 4 java apache apache-poi

我看到互联网上满是抱怨apache pdf产品的人,但是我在这里找不到我的特殊用例。我正在尝试使用apache poi做一个简单的Hello World。现在,我的代码如下:

public ByteArrayOutputStream export() throws IOException {
    //Blank Document
    XWPFDocument document = new XWPFDocument();

    //Write the Document in file system
    ByteArrayOutputStream out = new ByteArrayOutputStream();;

    //create table
    XWPFTable table = document.createTable();
    XWPFStyles styles = document.createStyles();
    styles.setSpellingLanguage("English");
    //create first row
    XWPFTableRow tableRowOne = table.getRow(0);
    tableRowOne.getCell(0).setText("col one, row one");
    tableRowOne.addNewTableCell().setText("col two, row one");
    tableRowOne.addNewTableCell().setText("col three, row one");

    //create second row
    XWPFTableRow tableRowTwo = table.createRow();
    tableRowTwo.getCell(0).setText("col one, row two");
    tableRowTwo.getCell(1).setText("col two, row two");
    tableRowTwo.getCell(2).setText("col three, row two");

    //create third row
    XWPFTableRow tableRowThree = table.createRow();
    tableRowThree.getCell(0).setText("col one, row three");
    tableRowThree.getCell(1).setText("col two, row three");
    tableRowThree.getCell(2).setText("col three, row three");

    PdfOptions options = PdfOptions.create();
    PdfConverter.getInstance().convert(document, out, options);
    out.close();
    return out;
}
Run Code Online (Sandbox Code Playgroud)

调用此代码是:

    public ResponseEntity<Resource> convertToPDFPost(@ApiParam(value = "DTOs passed from the FE" ,required=true )  @Valid @RequestBody ExportEnvelopeDTO exportDtos) {

        if (exportDtos.getProdExportDTOs() != null) {
            try {
                FileOutputStream out = new FileOutputStream("/Users/kornhaus/Desktop/test.pdf");
                out.write(exporter.export().toByteArray());
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return new ResponseEntity<Resource>(responseFile, responseHeaders, HttpStatus.OK);
        }

        return new ResponseEntity<Resource>(HttpStatus.INTERNAL_SERVER_ERROR);
    }

}
Run Code Online (Sandbox Code Playgroud)

在此行上:out.write(exporter.export().toByteArray()); 代码引发异常:

org.apache.poi.xwpf.converter.core.XWPFConverterException: java.io.IOException: Unable to parse xml bean
Run Code Online (Sandbox Code Playgroud)

我不知道是什么原因造成的,甚至在哪里也找不到这种文档。我从事编码已有十多年了,对于一个简单的Java库来说从来没有如此困难。任何帮助都会很棒。

Axe*_*ter 6

这样做的主要问题是这些PdfOptionsPdfConverter不是apache poi项目的一部分。它们是由开发的opensagres,第一个版本的命名错误org.apache.poi.xwpf.converter.pdf.PdfOptionsorg.apache.poi.xwpf.converter.pdf.PdfConverter。这些老班没有更新从2014年开始,需要版本3.9apache poi使用。

但是,相同的开发人员提供了fr.opensagres.poi.xwpf.converter.pdf,它是最新版本,并且使用最新的稳定版本进行工作apache poi 3.17。所以我们应该使用这个。

但是,因为即使是那些新的PdfOptionsPdfConverter的是不属于apache poi项目,apache poi将不测试那些与他们的版本。因此,*.docx由创建的默认文档apache poi缺少一些PdfConverter需要的内容。

  1. 即使为空,也必须有一个样式文档。

  2. 该页面必须具有至少设置了页面大小的部分属性。

  3. 表格必须设置表格网格。

为此,我们必须在程序中另外添加一些代码。不幸的是,这需要Faq-N10025中ooxml-schemas-1.3.jar提到的所有模式的完整jar 。

并且由于我们需要更改底层底层对象,因此必须编写文档,以便提交底层对象。否则XWPFDocument我们PdfConverter将不完整。

例:

import java.io.*;
import java.math.BigInteger;

//needed jars: fr.opensagres.poi.xwpf.converter.core-2.0.1.jar, 
//             fr.opensagres.poi.xwpf.converter.pdf-2.0.1.jar,
//             fr.opensagres.xdocreport.itext.extension-2.0.1.jar,
//             itext-2.1.7.jar                                  
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;

//needed jars: apache poi and it's dependencies
//             and additionally: ooxml-schemas-1.3.jar 
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.util.Units;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

public class XWPFToPDFConverterSampleMin {

 public static void main(String[] args) throws Exception {

  XWPFDocument document = new XWPFDocument();

  // there must be a styles document, even if it is empty
  XWPFStyles styles = document.createStyles();

  // there must be section properties for the page having at least the page size set
  CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
  CTPageSz pageSz = sectPr.addNewPgSz();
  pageSz.setW(BigInteger.valueOf(12240)); //12240 Twips = 12240/20 = 612 pt = 612/72 = 8.5"
  pageSz.setH(BigInteger.valueOf(15840)); //15840 Twips = 15840/20 = 792 pt = 792/72 = 11"

  // filling the body
  XWPFParagraph paragraph = document.createParagraph();

  //create table
  XWPFTable table = document.createTable();

  //create first row
  XWPFTableRow tableRowOne = table.getRow(0);
  tableRowOne.getCell(0).setText("col one, row one");
  tableRowOne.addNewTableCell().setText("col two, row one");
  tableRowOne.addNewTableCell().setText("col three, row one");

  //create CTTblGrid for this table with widths of the 3 columns. 
  //necessary for Libreoffice/Openoffice and PdfConverter to accept the column widths.
  //values are in unit twentieths of a point (1/1440 of an inch)
  //first column = 2 inches width
  table.getCTTbl().addNewTblGrid().addNewGridCol().setW(BigInteger.valueOf(2*1440));
  //other columns (2 in this case) also each 2 inches width
  for (int col = 1 ; col < 3; col++) {
   table.getCTTbl().getTblGrid().addNewGridCol().setW(BigInteger.valueOf(2*1440));
  }

  //create second row
  XWPFTableRow tableRowTwo = table.createRow();
  tableRowTwo.getCell(0).setText("col one, row two");
  tableRowTwo.getCell(1).setText("col two, row two");
  tableRowTwo.getCell(2).setText("col three, row two");

  //create third row
  XWPFTableRow tableRowThree = table.createRow();
  tableRowThree.getCell(0).setText("col one, row three");
  tableRowThree.getCell(1).setText("col two, row three");
  tableRowThree.getCell(2).setText("col three, row three");

  paragraph = document.createParagraph();

  //trying picture
  XWPFRun run = paragraph.createRun();
  run.setText("The picture in line: ");
  InputStream in = new FileInputStream("samplePict.jpeg");
  run.addPicture(in, Document.PICTURE_TYPE_JPEG, "samplePict.jpeg", Units.toEMU(100), Units.toEMU(30));
  in.close();  
  run.setText(" text after the picture.");

  paragraph = document.createParagraph();

  //document must be written so underlaaying objects will be committed
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  document.write(out);
  document.close();

  document = new XWPFDocument(new ByteArrayInputStream(out.toByteArray()));
  PdfOptions options = PdfOptions.create();
  PdfConverter converter = (PdfConverter)PdfConverter.getInstance();
  converter.convert(document, new FileOutputStream("XWPFToPDFConverterSampleMin.pdf"), options);

  document.close();

 }
}
Run Code Online (Sandbox Code Playgroud)

使用XDocReport

另一种方式是使用Converteragres / xdocreport的最新版本,如Converter中仅对ConverterRegistry所述

import java.io.*;
import java.math.BigInteger;

//needed jars: xdocreport-2.0.1.jar, 
//             odfdom-java-0.8.7.jar,
//             itext-2.1.7.jar  
import fr.opensagres.xdocreport.converter.Options;
import fr.opensagres.xdocreport.converter.IConverter;
import fr.opensagres.xdocreport.converter.ConverterRegistry;
import fr.opensagres.xdocreport.converter.ConverterTypeTo;
import fr.opensagres.xdocreport.core.document.DocumentKind;

//needed jars: apache poi and it's dependencies
//             and additionally: ooxml-schemas-1.3.jar 
import org.apache.poi.xwpf.usermodel.*;
import org.apache.poi.util.Units;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

public class XWPFToPDFXDocReport {

 public static void main(String[] args) throws Exception {

  XWPFDocument document = new XWPFDocument();

  // there must be a styles document, even if it is empty
  XWPFStyles styles = document.createStyles();

  // there must be section properties for the page having at least the page size set
  CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
  CTPageSz pageSz = sectPr.addNewPgSz();
  pageSz.setW(BigInteger.valueOf(12240)); //12240 Twips = 12240/20 = 612 pt = 612/72 = 8.5"
  pageSz.setH(BigInteger.valueOf(15840)); //15840 Twips = 15840/20 = 792 pt = 792/72 = 11"

  // filling the body
  XWPFParagraph paragraph = document.createParagraph();

  //create table
  XWPFTable table = document.createTable();

  //create first row
  XWPFTableRow tableRowOne = table.getRow(0);
  tableRowOne.getCell(0).setText("col one, row one");
  tableRowOne.addNewTableCell().setText("col two, row one");
  tableRowOne.addNewTableCell().setText("col three, row one");

  //create CTTblGrid for this table with widths of the 3 columns. 
  //necessary for Libreoffice/Openoffice and PdfConverter to accept the column widths.
  //values are in unit twentieths of a point (1/1440 of an inch)
  //first column = 2 inches width
  table.getCTTbl().addNewTblGrid().addNewGridCol().setW(BigInteger.valueOf(2*1440));
  //other columns (2 in this case) also each 2 inches width
  for (int col = 1 ; col < 3; col++) {
   table.getCTTbl().getTblGrid().addNewGridCol().setW(BigInteger.valueOf(2*1440));
  }

  //create second row
  XWPFTableRow tableRowTwo = table.createRow();
  tableRowTwo.getCell(0).setText("col one, row two");
  tableRowTwo.getCell(1).setText("col two, row two");
  tableRowTwo.getCell(2).setText("col three, row two");

  //create third row
  XWPFTableRow tableRowThree = table.createRow();
  tableRowThree.getCell(0).setText("col one, row three");
  tableRowThree.getCell(1).setText("col two, row three");
  tableRowThree.getCell(2).setText("col three, row three");

  paragraph = document.createParagraph();

  //trying picture
  XWPFRun run = paragraph.createRun();
  run.setText("The picture in line: ");
  InputStream in = new FileInputStream("samplePict.jpeg");
  run.addPicture(in, Document.PICTURE_TYPE_JPEG, "samplePict.jpeg", Units.toEMU(100), Units.toEMU(30));
  in.close();  
  run.setText(" text after the picture.");

  paragraph = document.createParagraph();

  //document must be written so underlaaying objects will be committed
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  document.write(out);
  document.close();

  // 1) Create options DOCX 2 PDF to select well converter form the registry
  Options options = Options.getFrom(DocumentKind.DOCX).to(ConverterTypeTo.PDF);

  // 2) Get the converter from the registry
  IConverter converter = ConverterRegistry.getRegistry().getConverter(options);

  // 3) Convert DOCX 2 PDF
  InputStream docxin= new ByteArrayInputStream(out.toByteArray());
  OutputStream pdfout = new FileOutputStream(new File("XWPFToPDFXDocReport.pdf"));
  converter.convert(docxin, pdfout, options);

  docxin.close();       
  pdfout.close();       

 }
}
Run Code Online (Sandbox Code Playgroud)

2018年10月:此代码可使用apache poi 3.17。使用它不能工作,apache poi 4.0.0由于changings apache poi其未在帐户中取到现在为止fr.opensagres.poi.xwpf.converter,以及在fr.opensagres.xdocreport.converter


2019年2月:对我的作品现在使用的最新apache poi版本4.0.1和最新版本2.0.2fr.opensagres.poi.xwpf.converter.core和配偶。