How to convert doc to pdf file using itext

*爱你&永不变心* 提交于 2019-12-16 18:04:06

问题


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.



来源:https://stackoverflow.com/questions/10349396/how-to-convert-doc-to-pdf-file-using-itext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!