How to convert doc to pdf file using itext

2019-09-19 11:30发布

问题:

I need how to convert doc to pdf file using itext.

I am using the following code it is not working. i am using itext 2.1.7.jar.

The following error is coming:

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) 

Here's my 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:

You didn't add any content to the PDF document (just an empty new page). To add actual content, use the add(Element) method of the Document class.