java替换word文档书签并转换为pdf

时间:2017-05-11 06:24:51

标签: java itext apache-poi

我尝试使用apache poi替换word文档书签并将其转换为pdf。它看起来必须有效,但我有许多错误相互联系。我解决了一个,然后在这里出现下一个。我做错了什么?我必须拥有哪些图书馆?

1 个答案:

答案 0 :(得分:3)

首先使用maven下载必要的jar文件,而不是手动。 pom.xml文件看起来像:

<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>fr.opensagres.xdocreport</groupId>
      <artifactId>org.apache.poi.xwpf.converter.core</artifactId>
      <version>1.0.5</version>
    </dependency>

    <dependency>
      <groupId>fr.opensagres.xdocreport</groupId>
      <artifactId>org.apache.poi.xwpf.converter.pdf</artifactId>
      <version>1.0.5</version>
    </dependency>

    <dependency>
      <groupId>fr.opensagres.xdocreport</groupId>
      <artifactId>org.apache.poi.xwpf.converter.xhtml</artifactId>
      <version>1.0.5</version>
    </dependency>
  </dependencies>

将下载以下jar文件:

enter image description here

我还写了一些java代码,希望会派上用场:

package com.company;


import com.lowagie.text.pdf.BaseFont;
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBookmark;
import org.w3c.dom.Node;

import java.io.*;
import java.util.Iterator;
import java.util.List;


public class Main {


    public static class DOCXTest {

        public XWPFDocument document = null;

        public  DOCXTest() {
        }

        public  final void openFile(String filename) throws IOException {
            File file = null;
            FileInputStream fis = null;
            try {
                file = new File(filename);
                fis = new FileInputStream(file);
                this.document = new XWPFDocument(fis);
            }
            finally {
                try {
                    if(fis != null) {
                        fis.close();
                        fis = null;
                    }
                }
                catch(IOException ioEx) {
                }
            }
        }

        public final void saveAs(String filename) throws IOException {
            File file = null;
            FileOutputStream fos = null;
            try {
                file = new File(filename);
                fos = new FileOutputStream(file);
                this.document.write(fos);
            }
            finally {
                if(fos != null) {
                    fos.close();
                    fos = null;
                }
            }
        }




        private final void procParaList(List<XWPFParagraph> paraList,
                                        String bookmarkName, String bookmarkValue) {
            Iterator<XWPFParagraph> paraIter = null;
            XWPFParagraph para = null;
            List<CTBookmark> bookmarkList = null;
            Iterator<CTBookmark> bookmarkIter = null;
            CTBookmark bookmark = null;
            XWPFRun run = null;
            Node nextNode = null;

            paraIter = paraList.iterator();
            while(paraIter.hasNext()) {
                para = paraIter.next();
                bookmarkList = para.getCTP().getBookmarkStartList();
                bookmarkIter = bookmarkList.iterator();

                while(bookmarkIter.hasNext()) {
                    bookmark = bookmarkIter.next();
                    if(bookmark.getName().equals(bookmarkName)) {
                        run = para.createRun();
                        run.setText(bookmarkValue);
                        nextNode = bookmark.getDomNode().getNextSibling();
                        while(!(nextNode.getNodeName().contains("bookmarkEnd"))) {
                            para.getCTP().getDomNode().removeChild(nextNode);
                            nextNode = bookmark.getDomNode().getNextSibling();
                        }
                        para.getCTP().getDomNode().insertBefore(
                                run.getCTR().getDomNode(),
                                nextNode);
                    }
                }
            }
        }


        public final void insertAtBookmark(String bookmarkName, String bookmarkValue) {
            List<XWPFTable> tableList = null;
            Iterator<XWPFTable> tableIter = null;
            List<XWPFTableRow> rowList = null;
            Iterator<XWPFTableRow> rowIter = null;
            List<XWPFTableCell> cellList = null;
            Iterator<XWPFTableCell> cellIter = null;
            XWPFTable table = null;
            XWPFTableRow row = null;
            XWPFTableCell cell = null;

            this.procParaList(this.document.ge
            tableList = this.document.getTables();
            tableIter = tableList.iterator();
            while(tableIter.hasNext()) {
                table = tableIter.next();
                rowList = table.getRows();
                rowIter = rowList.iterator();
                while(rowIter.hasNext()) {
                    row = rowIter.next();
                    cellList = row.getTableCells();
                    cellIter = cellList.iterator();
                    while(cellIter.hasNext()) {
                        cell = cellIter.next();
                        this.procParaList(cell.getParagraphs(),
                                bookmarkName,
                                bookmarkValue);
                    }
                }
            }
        }


    }



    public static boolean LogEnabled = true;



    public static void main(String[] args) {
        AddLog("Start");
        try {

            DOCXTest docxTest = new DOCXTest();
            docxTest.openFile("D:/template.docx");
            docxTest.insertAtBookmark("FIO", "Ibadov Kamil Ələsgər");
            docxTest.saveAs("D:/replaced.docx");
            File outFile = new File("D:/replaced.pdf");
            outFile.getParentFile().mkdirs();

            OutputStream out = new FileOutputStream(outFile);
            PdfOptions options = PdfOptions.create().fontEncoding(BaseFont.IDENTITY_H);
            PdfConverter.getInstance().convert(docxTest.document, out, options);


            AddLog("End");

        } catch (Exception e) {
            AddLog(e.getMessage());
        }
    }


    public static void AddLog(String LogMessage) {
        if (LogEnabled) {
            try {
                System.out.println(LogMessage);
                BufferedWriter out = new BufferedWriter(new FileWriter("logs.txt"));
                out.write(LogMessage);
                out.close();
            }
            catch (IOException e)
            {
                System.out.println("Exception ");
            }

        }

    }


}