我该怎么做才能制作我的程序(另存为像Microsoft Excel这样的pdf文件)

时间:2013-05-08 14:33:58

标签: java

当我将xls文件保存为pdf格式时,是否可以制作(调用)或执行相同操作的程序。 在java程序中使用JAVA API Jxl或其他东西

我找到了一个例子

import officetools.OfficeFile; // from officetools.jar

FileInputStream fis = new FileInputStream(new File("test.doc")); 
FileOutputStream fos = new FileOutputStream(new File("test.pdf"));

OfficeFile f = new OfficeFile(fis,"localhost","8100", false);

f.convert(fos,"pdf");

但是它需要openOffice还有像Excel上的PDF crator那样在我的程序上自动更改扩展名

1 个答案:

答案 0 :(得分:1)

在此处查看此示例Covert doc, excel, text and images to PDF,该示例使用iText和apache poi

http://itextpdf.com/下载iText

来自http://poi.apache.org/download.html

的aplaod apache poi

您也可以使用以下示例将Microsoft Office Word文件转换为PDF

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;


import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;

import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;


public class DocToPDF{

public static void main(String[] args) {

    POIFSFileSystem fs = null;  
    Document document = new Document();

     try {  

         fs = new POIFSFileSystem(new FileInputStream("D:/test.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, file);  

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

         // add the paragraph to the document  
         document.add(new Paragraph(paragraphs[i]));  
         }  

         System.out.println("Finished");  
     } catch (Exception e) {  
         e.printStackTrace();  
     } finally {  
                     // close the document  
        document.close();  
                 }  
     }  
}