利用 ICEpdf 快速實現 pdf 檔案預覽功能

來源:互聯網
上載者:User

標籤:

之前工作中,需要實現一個線上預覽pdf的功能,一開始用的的 jQuery-media 外掛程式來實現的,後來感覺有點慢,就繼續尋找更好的替代品,直到遇見了 ICE pdf。。。

ICEpdf (官網:http://www.icesoft.org/java/home.jsf) 原理是基於 Java SE 中的 Swing 實現的 (誰說 Swing 沒有用武之地了。。。) ,將一個 PDF 檔案作為一個 Document 對象,調用封裝的方法,將該檔案的每一頁產生一張圖片!

關鍵代碼如下:

public static void main(String[] args) {        String filePath = "test.pdf";        // open the file        Document document = new Document();        try {            document.setFile(filePath);        } catch (PDFException e) {            System.out.println("parsing PDF document failure" + e);        } catch (PDFSecurityException e) {            System.out.println("encrytion not supported " + e);        } catch (IOException e) {            System.out.println("IOException " + e);        }        // save page captures to file        float scale = 2.0f;        float rotation = 360f;        // Paint each pages content to an image and write the image to file        System.out.println("The number of page: " + document.getNumberOfPages());        for (int i = 0; i < 5; i++) {            BufferedImage image = (BufferedImage) document.getPageImage(i, GraphicsRenderingHints.PRINT, Page.BOUNDARY_TRIMBOX, rotation, scale);            try {                System.out.println("capturing page: " + i);                File file = new File("imageCapture_" + i + ".png");                ImageIO.write(image, "png", file);            } catch (IOException e) {                e.printStackTrace();            }            image.flush();        }        // clean up resources        document.dispose();    }

我的 jar 包用的是 icepdf-core-6.0.0.jar ,

首先,聲明一個 Document 對象,調用 setFile(String filePath) 方法,參數為 pdf 絕對或者相當路徑;

變數 scale 代表放縮比例,預設為 1,越大產生的圖片越清晰;

變數 rotation 為旋轉角度,360度一個周期,可以設定任意值試試;

然後調用 getPageImage() 方法,產生圖片流,然後對圖片進行處理,可以輸出到本地,也可以以流的形式傳到頁面,實現快速預覽的效果。

最後,我利用這個功能,在首次預覽時,產生對應頁碼圖片到本地或者伺服器,第二次預覽則直接查看圖片,使得使用者體驗更好~

利用 ICEpdf 快速實現 pdf 檔案預覽功能

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.