java将WORD文档转换成pdf文件

总结对jacob和Itext学习总结.本文试验的是将WORD转换成PDF文件.

实现思路

一、先将WORD文档转换成HMTL文件格式(参阅我的前一文《JAVA操作WORD文档)。

二、用流读取HTML文件。将其保存在一个String对象中。

三、用Itext组件,将生成的字符串对象转换成PDF文件。

四、在要生成的PDF文件加入所需信息。

在此:有几点问题如还请前辈解答:1、怎么控制我在PDF文件加入某段文字的字体、大小、间距等。

/**
 * 生成PDF文件
 * @author 于学明
 *
 */
public class CreatePdf {

/**
 * 获得PDF文件所需图片
 * @param imagePath  //图片文件路径
 * @return
 * @throws BadElementException
 * @throws MalformedURLException
 * @throws IOException
 */
 public Image getImageFile(String imagePath) throws BadElementException, MalformedURLException, IOException{
  Image jpg = Image.getInstance(imagePath);
  //设置图片居中
  jpg.setAlignment(Image.MIDDLE);
  return jpg;
 }
 
 /**
  * 获得文字内容
  * @param inputFilePath 原DOC文件路径
  * @param outputFilePath 生成HTML文件路径
  * @return
  */
 public String getPdfContext(String inputFilePath,String outputFilePath){
//  读取DOC文件内容
  String htmlText = new FileExtracter().extractDoc(inputFilePath, outputFilePath);
  //把读取的HTML文件,生成一个字符串
  String pdf =  new FileExtracter().getContext(htmlText);
  
  return pdf;
 }
 /**
  * 用ITEXT生成指定PDF格式文件
  * @param imagePath0
  * @param inputFilePath
  * @param outputFilePath
  * @param imagePath1
  * @param outputPdf
  * @return
  * @throws DocumentException
  * @throws IOException
  */
 public String createPDF(String imagePath0,String inputFilePath,String outputFilePath,String imagePath1,String outputPdf) throws DocumentException, IOException{
  
  //返回的pdf全路径  
  String returnPdf="";  
  File dir=new File("out_pdf");
  //若目录不存在则新建该目录
  if(!dir.exists()){
   dir.mkdir();
  }
    
  //新建空白文件
  File outPdfPath=new File(dir+"/"+outputPdf);//输出pdf文件的全路径
  try {
   outPdfPath.createNewFile();
  } catch (IOException e1) {
   e1.printStackTrace();
   returnPdf=null;
  }
  //定义PDF文件大小和边距
  Document document = new Document(PageSize.A4, 50, 50, 50, 50);  
  //生成PDF文件的路径
  PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream(outPdfPath));
  writer.setViewerPreferences(PdfWriter.PageModeFullScreen);
  document.open();
  //文件头图片
  document.add(getImageFile(imagePath0));
  //定义字体,可以正常显示中文
  BaseFont bfComic = BaseFont.createFont("STSong-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
  Font font = new Font(bfComic, 12, Font.NORMAL);
    
  String pdf =  getPdfContext(inputFilePath, outputFilePath);
//  String str=new String(pdf.getBytes("ISO-8859-1"),"GB2312");
  document.add(new Paragraph(pdf,font));
  //文件尾图片
  document.add(getImageFile(imagePath1));
  document.close();
  returnPdf = outPdfPath.getAbsolutePath();
  return returnPdf;
 }
 
 /**
  *  用ITEXT生成指定PDF格式文件
  * @param imagePath
  * @param inputFilePath
  * @param outputFilePath
  * @param outputPdf
  * @return
  * @throws DocumentException
  * @throws IOException
  */
 public String createPDF(String imagePath,String inputFilePath,String outputFilePath,String outputPdf) throws DocumentException, IOException{
  
  //  返回的pdf全路径  
  String returnPdf="";  
  File dir=new File("out_pdf");
  //若目录不存在则新建该目录
  if(!dir.exists()){
   dir.mkdir();
  }
    
  //新建空白文件
  File outPdfPath=new File(dir+"/"+outputPdf);//输出pdf文件的全路径
  try {
   outPdfPath.createNewFile();
  } catch (IOException e1) {
   e1.printStackTrace();
   returnPdf=null;
  }
  Document document = new Document(PageSize.A4, 50, 50, 50, 50);  
  //生成PDF文件的路径
  PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream(outPdfPath));
  writer.setViewerPreferences(PdfWriter.PageModeFullScreen);
  document.open();  
  document.add(getImageFile(imagePath));
//  定义字体,可以正常显示中文
  BaseFont bfComic = BaseFont.createFont("STSong-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
  Font font = new Font(bfComic, 12, Font.NORMAL);
    
  String pdf =  getPdfContext(inputFilePath, outputFilePath);
//  String str=new String(pdf.getBytes("ISO-8859-1"),"GB2312");
  document.add(new Paragraph(pdf,font));
  document.close();
  returnPdf = outPdfPath.getAbsolutePath();
  return returnPdf;
 }

 public static void main(String [] args){
  
  try {
   String s = new CreatePdf().createPDF("c:/a.gif","c:/s.doc", "c:/x.html", "a.pdf");
   System.out.println(s);
  } catch (DocumentException e) {
   // TODO 自动生成 catch 块
   e.printStackTrace();
  } catch (IOException e) {
   // TODO 自动生成 catch 块
   e.printStackTrace();
  }
 }
}
 

Java中,将Word文档(.doc或.docx格式)换为PDF通常需要借助第三方库,因为Java标准库本身并不直接提供这样的功能。一个常用的工具是Apache POI,它用于处理Microsoft Office文件格式,包括读取Word文档,而iText或Flying Saucer等库则可以用来生成PDF。 以下是一个简化的步骤: 1. 首先,你需要添加Apache POI和PDF库到项目中。对于POI,可以使用`poi`和`poi-ooxml`依赖;对于iText,引入`itextpdf`库。 ```java // Maven坐标示例 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.x.x</version> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.x.x</version> </dependency> ``` 2. 使用Apache POI读取Word文档内容。例如,你可以创建`Document`对象并加载Word文档。 ```java Document document = new Document(); InputStream is = new FileInputStream("input.docx"); POIXMLDocument doc = POIXMLDocument.openPackage(is); ``` 3. 解析Word文档中的元素,如Paragraphs、Tables等,并将其复制到一个新的PDF文档。 ```java XWPFDocument xwpfDoc = new XWPFDocument(doc); for (XWPFParagraph paragraph : xwpfDoc.getParagraphs()) { // 处理每个段落 } List<XWPFTable> tables = xwpfDoc.getTables(); for (XWPFTable table : tables) { // 处理每个表格 } ``` 4. 使用iText或类似库创建PDF文档,并将Word的内容添加进去。这通常涉及创建一个新的PdfDocument对象,然后添加节(Sections)和内容。 ```java try (Document pdfDoc = new Document()) { PdfWriter.getInstance(pdfDoc, new FileOutputStream("output.pdf")); pdfDoc.open(); // 将Word内容换为PDF for (Paragraph p : paragraphs) { Element element = p.createStyledElement(Element.TEXT); pdfDoc.add(element); } for (Table t : tables) { PdfPTable pdfTable = new PdfPTable(t.getRowArray().length); // 添加表格行到PDF表 } pdfDoc.close(); } ```
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值