2012-04-27 109 views
0

我需要如何使用itext将doc转换为pdf文件。我使用下面的代码,它不工作。我正在使用itext 2.1.7.jar。下面的错误来了如何使用itext将文档转换为pdf文件

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(); 
    } 

请任何人的帮助。

回答

0

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

+0

我在Result1.doc文件中添加了一些内容 – 2012-04-27 11:29:59

+0

对不起,我的意思是你没有向PDF文档添加任何内容,让我编辑我的回复。 – 2012-04-27 11:54:05

+0

是的,我没有添加任何内容的PDF文件 – 2012-04-28 04:16:39