Вероятно, это копия Попытка создать простой PDF-документ с Apache poi . Но давайте снова приведем полный пример, чтобы показать, как создать новый XWPFDocument
с нуля, используя последнюю версию apache poi 4.1.2
, которая затем может быть преобразована в PDF
с использованием PdfConverter
из fr.opensagres.poi.xwpf.converter
версии 2.0.2
и iText
.
Как сказано в документах по умолчанию *.docx
, созданных apache poi
, отсутствует контент, который необходим PdfConverter
.
Должен существовать документ стилей, даже если он пустой.
И должны быть свойства раздела для страницы, для которой установлен хотя бы размер страницы. Для этого мы должны добавить код в нашу программу. К сожалению, для этого нужен полный jar всех схем ooxml-schemas-1.4.jar
, как указано в Faq-N10025 .
И поскольку нам нужно изменить базовые объекты низкого уровня, документ должен быть написан поэтому основные объекты будут зафиксированы. В противном случае XWPFDocument
, который мы передаем PdfConverter
, будет неполным.
Минимальный полный рабочий пример:
import java.io.*;
import java.math.BigInteger;
//needed jars: fr.opensagres.poi.xwpf.converter.core-2.0.2.jar,
// fr.opensagres.poi.xwpf.converter.pdf-2.0.2.jar,
// fr.opensagres.xdocreport.itext.extension-2.0.2.jar,
// itext-4.2.1.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.4.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();
XWPFRun title = paragraph.createRun();
title.setText("gLETS GO");
//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();
}
}