如何使用itext将doc转换为pdf文件

时间:2012-04-27 10:58:38

标签: java itext apache-poi

我需要如何使用itext将doc转换为pdf文件。

我使用以下代码无效。我正在使用itext 2.1.7.jar。

以下错误即将发生:

Exception in thread "main" ExceptionConverter: java.io.IOException: The document
    has no pages.at com.lowagie.text.pdf.PdfPages.writePageTree(Unknown Source)
at com.lowagie.text.pdf.PdfWriter.close(Unknown Source)
at com.lowagie.text.pdf.PdfDocument.close(Unknown Source)
at com.lowagie.text.Document.close(Unknown Source) 

这是我的来源:

    POIFSFileSystem fs = null;  
    Document document = new Document();
     try {  
         System.out.println("Starting the test");  
         fs = new POIFSFileSystem(new FileInputStream("D:\\Result1.doc"));  

         HWPFDocument doc = new HWPFDocument(fs);  
         WordExtractor we = new WordExtractor(doc); 

         //OutputStream file = new FileOutputStream(new File("D:\\test.pdf"));
         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("D:\\test.pdf"));  
              Range range = doc.getRange();
         document.open();  
         writer.setPageEmpty(true);  
         document.newPage();  
         writer.setPageEmpty(true);  
         String[] paragraphs = we.getParagraphText();  
         for (int i = 0; i < paragraphs.length; i++) {  
             org.apache.poi.hwpf.usermodel.Paragraph pr = range.getParagraph(i);
             paragraphs[i] = paragraphs[i].replaceAll("\\cM?\r?\n", "");  
         System.out.println("Length:" + paragraphs[i].length());  
         System.out.println("Paragraph" + i + ": " + paragraphs[i].toString());  
         }  
         System.out.println("Document testing completed");  
     } catch (Exception e) {  
         System.out.println("Exception during test");  
         e.printStackTrace();  
     } finally {  
         document.close();  
     }  

1 个答案:

答案 0 :(得分:0)

您没有向PDF文档添加任何内容(只是一个空的新页面)。要添加实际内容,请使用Document类的add(Element)方法。