关于POI提取word中文本,除掉页眉页脚

需要相关七个jar

poi-3.7-20101029.jar

poi-ooxml-3.7-20101029.jar

poi-ooxml-schemas-3.7-20101029.jar

poi-scratchpad-3.7-20101029.jar

dom4j-1.6.1.jar

geronimo-stax-api_1.0_spec-1.0.jar

xmlbeans-2.3.0.jar

 

public static String wordExtractor(String fileName){
  try{
  InputStream in = new FileInputStream(fileName);
  String header,footer,allText;
  int end;
  if(getSuffix(fileName).equals("doc")){
  WordExtractor wordExtractor = new WordExtractor(in);
  header = wordExtractor.getHeaderText();
  footer = wordExtractor.getFooterText();
  allText = wordExtractor.getText();
  end = allText.indexOf(footer);
  return allText.substring(header.length(), end);
  }else if(getSuffix(fileName).equals("docx")){
   OPCPackage opcPackage =  POIXMLDocument.openPackage(fileName);   
   POIXMLTe

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
根据提供的引用[1],Apache POI是一个Java API,可用于读取和编写Microsoft Office二进制文件格式,例如doc、xls和ppt等。但是,它不支持将Word文档直接转换为PDF格式。因此,我们需要使用其他库来实现将Word文档转换为PDF格式。在此过程中,我们可以使用Apache PDFBox库来添加页眉和页。以下是实现此目的的步骤: 1. 首先,我们需要将Word文档转换为PDF格式。我们可以使用Apache POI库中的XWPFDocument类来读取Word文档,并使用Apache PDFBox库中的PDFMergerUtility类将其转换为PDF格式。以下是示例代码: ```java // 读取Word文档 XWPFDocument document = new XWPFDocument(new FileInputStream("input.docx")); // 将Word文档转换为PDF格式 ByteArrayOutputStream baos = new ByteArrayOutputStream(); PdfOptions options = PdfOptions.create(); PdfConverter.getInstance().convert(document, baos, options); baos.flush(); baos.close(); byte[] pdfBytes = baos.toByteArray(); // 将PDF字节数组写入文件 FileOutputStream fos = new FileOutputStream("output.pdf"); fos.write(pdfBytes); fos.close(); ``` 2. 接下来,我们可以使用Apache PDFBox库中的PDFTextStripper类来添加页眉和页。以下是示例代码: ```java // 读取PDF文档 PDDocument document = PDDocument.load(new File("output.pdf")); // 添加页眉和页 PDPageTree pages = document.getPages(); for (PDPage page : pages) { PDPageContentStream contentStream = new PDPageContentStream(document, page, AppendMode.APPEND, true, true); contentStream.beginText(); contentStream.setFont(PDType1Font.TIMES_ITALIC, 10); contentStream.newLineAtOffset(50, 750); contentStream.showText("页眉"); contentStream.endText(); contentStream.beginText(); contentStream.setFont(PDType1Font.TIMES_ITALIC, 10); contentStream.newLineAtOffset(50, 50); contentStream.showText("页"); contentStream.endText(); contentStream.close(); } // 保存PDF文档 document.save("output_with_header_footer.pdf"); document.close(); ``` 以上代码将在每个页面的顶部添加“页眉”文本,并在每个页面的底部添加“页”文本。您可以根据需要更改文本内容和位置。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值