PDFOne Java如何从URL读取PDF文件

作者:控件中国网   出处:控件中国网   2015-10-13 10:27:43   阅读:13

PDFOne Java是一款PDF文档处理控件,可以通过该控件创建基于J2SE、J2EE下的PDF文档处理应用,PDFOne Java可以从本地、流、字节数组的形式读取PDF文件,这篇文章主要介绍如何从互联网上加载PDF文件,具体可以参考下面的详细代码:

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.net.ConnectException;

import java.net.URL;

import java.net.URLConnection;

import com.Gnostice.pdfone.PdfDocument;

public class Read_PDF_From_URL {

  public static void main(String[] args) throws IOException {

    URL url1 =

      new URL("http://www.Gnostice.com/downloads/Gnostice_PathQuest.pdf");

    byte[] ba1 = new byte[1024];

    int baLength;

    FileOutputStream fos1 = new FileOutputStream("download.pdf");

    try {

      // Contacting the URL

      System.out.print("Connecting to " + url1.toString() + " ... ");

      URLConnection urlConn = url1.openConnection();

      // Checking whether the URL contains a PDF

      if (!urlConn.getContentType().equalsIgnoreCase("application/pdf")) {

          System.out.println("FAILED.\n[Sorry. This is not a PDF.]");

      } else {

        try {

          // Read the PDF from the URL and save to a local file

          InputStream is1 = url1.openStream();

          while ((baLength = is1.read(ba1)) != -1) {

              fos1.write(ba1, 0, baLength);

          }

          fos1.flush();

          fos1.close();

          is1.close();

          // Load the PDF document and display its page count

          System.out.print("DONE.\nProcessing the PDF ... ");

          PdfDocument doc = new PdfDocument();

          try {

            doc.load("download.pdf");

            System.out.println("DONE.\nNumber of pages in the PDF is " +

                               doc.getPageCount());

            doc.close();

          } catch (Exception e) {

            System.out.println("FAILED.\n[" + e.getMessage() + "]");

          }

        } catch (ConnectException ce) {

          System.out.println("FAILED.\n[" + ce.getMessage() + "]\n");

        }

      }

    } catch (NullPointerException npe) {

      System.out.println("FAILED.\n[" + npe.getMessage() + "]\n");

    }

  }

}

Copyright© 2006-2015 ComponentCN.com all rights reserved.重庆磐岩科技有限公司(控件中国网) 版权所有 渝ICP备12000264号 法律顾问:元炳律师事务所
客服软件
live chat