我在iText封裝的方法,從某個pdf檔案中獲得指定的頁

來源:互聯網
上載者:User

查了一堆資料,終於從2on1這個例子中有所啟示,根據這個改造的方法。

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfWriter;

public class PDFUtil {
 public static PdfImportedPage getPage(String file_name,int i){
  
  try {
   File out = new File("2on1.pdf"); // 建立一個輸出的臨時檔案
   FileOutputStream outfile = new FileOutputStream(out);
   PdfReader reader = new PdfReader(file_name);  // 建立reader
   Rectangle psize = reader.getPageSize(1);
   float width = psize.height();
   float height = psize.width();

   // step 1: creation of a document-object
   Document document = new Document(new Rectangle(width, height)); // 建立檔案的大小,以前因為沒有建立document造成了經常報nullpoint
   PdfWriter writer = PdfWriter.getInstance(document,outfile);
   document.open();
   PdfImportedPage page1 = writer.getImportedPage(reader, i);
   writer.freeReader(reader);
   reader = null;
   writer = null;
   outfile.close();

   return page1;
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (DocumentException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return null;
 }
}
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.