MailMerge并使用Apache-POI将Docx转换为PDF-Java

时间:2018-10-10 22:30:20

标签: java apache-poi xwpf

我有一个具有合并字段的docx文件。它包含一个xls文件以生成多个记录。 docx中的每个记录都链接到xls文件中的一个记录。当我使用apache poi将此docx转换为pdf时,它仅转换第一条记录。如何转换所有记录? 这是我所做的:

import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

public class Doc2PDF {

    /**
     * @param args the command line arguments
     */
    public static final String SOURCE_DOCX = "N:\\HSV_Letter1.docx";
    public static final String TARGET_PDF = "N:\\HSV.pdf";

    public static void main(String[] args) {
        // TODO code application logic here
        Doc2PDF cwoWord = new Doc2PDF();
        System.out.println("Start");
        cwoWord.ConvertToPDF(SOURCE_DOCX, TARGET_PDF);

    }

    public void ConvertToPDF(String docPath, String pdfPath) {
        try {
            InputStream doc = new FileInputStream(new File(docPath));
//            XWPFDocument document = new XWPFDocument(new File(docPath).toURI().toURL().openStream());
            XWPFDocument document = new XWPFDocument(doc);
            PdfOptions options = PdfOptions.create();
            OutputStream out = new FileOutputStream(new File(pdfPath));
            PdfConverter.getInstance().convert(document, out, options);
            System.out.println("Done");
        } catch (FileNotFoundException ex) {
            System.out.println(ex.getMessage());
        } catch (IOException ex) {

            System.out.println(ex.getMessage());
        }
    }

}

0 个答案:

没有答案