java将word转成pdf
时间: 2023-09-08 16:10:57 浏览: 155
java将word转pdf
要将Word文档转换为PDF文件,可以使用Apache POI和iText库。以下是一个示例代码:
```
import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.WordToPdfConverter;
import org.apache.poi.hwpf.usermodel.Range;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
public class WordToPDFConverter {
public static void main(String[] args) {
String inputFile = "input.doc";
String outputFile = "output.pdf";
try (FileInputStream fis = new FileInputStream(inputFile);
HWPFDocument doc = new HWPFDocument(fis);
OutputStream fileOutputStream = new FileOutputStream(outputFile);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
Range range = doc.getRange();
WordToPdfConverter converter = new WordToPdfConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
converter.processDocument(doc, range, byteArrayOutputStream);
Document pdfDoc = new Document();
PdfWriter.getInstance(pdfDoc, fileOutputStream);
pdfDoc.open();
pdfDoc.addCreator("Word to PDF Converter");
pdfDoc.addTitle("Converted from Word document");
pdfDoc.addSubject("PDF document generated from Word document");
ByteArrayInputStream in = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
int bytesRead;
byte[] buffer = new byte[4096];
while ((bytesRead = in.read(buffer)) != -1) {
pdfDoc.add(new com.itextpdf.text.Paragraph(new String(buffer, 0, bytesRead)));
}
pdfDoc.close();
System.out.println("Conversion complete.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在这个示例中,我们使用两个库:Apache POI和iText。我们首先打开Word文档,并使用`WordToPdfConverter`将其转换为PDF。然后,我们创建一个新的PDF文档,并将转换后的内容写入其中。最后,我们关闭PDF文档并完成转换。
阅读全文