【问题标题】:how to download a url as pdf in local file?如何在本地文件中将 url 下载为 pdf 格式?
【发布时间】:2014-12-10 16:14:11
【问题描述】:

我正在尝试将以下网址下载为本地文件夹中的 pdf 文件。

http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=1498781&tag=1

到目前为止我尝试过的是:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class DownloadPDF {

    public DownloadPDF () {}


    public static String download (String link, String i) {
         String save = null;

         try{
             String file = link;
             URL url = new URL(file);
             InputStream in = url.openStream();
             save = "local_folder/name.pdf";    
             FileOutputStream fos = new FileOutputStream(new File(save));

             int length = -1;
             byte[] buffer = new byte[1024];

            while ((length = in.read(buffer)) > -1) {
                 fos.write(buffer, 0, length);
            }
            fos.close();
            in.close();
            System.out.println("file is downloaded");

       } catch (IOException e) {
            e.printStackTrace();
       }
       return save;
    }  
}

这适用于:

http://ongambling.org/wp-content/uploads/2011/02/binde-2005-jgs-postprint.pdf

但不适用于上面给出的第一个网址?还有其他建议吗?

【问题讨论】:

标签: java pdf download


【解决方案1】:

您在点击您的网址时呈现您的 pdf,这将是最佳选择。否则检查参数然后

试试这个

            ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
            hwb.write(outByteStream);
            byte [] outArray = outByteStream.toByteArray();
            response.setContentType("application/pdf");
            response.setContentLength(outArray.length);
            response.setHeader("Expires:", "0"); // eliminates browser caching
            response.setHeader("Content-Disposition", "attachment; filename="+fname);
            OutputStream outStream = response.getOutputStream();
            outStream.write(outArray);
            outStream.flush();
            response.sendRedirect("servlet?id=2");

【讨论】:

    【解决方案2】:

    第一个网址对应于 pdf 文件。当您实际进入该页面时,您只需以按钮的形式选择sign-inpurchase。现在,如果您偶然购买了 pdf,因此该页面会将您重定向到它的在线版本;您将不得不看看通过 Java 在网页上进行身份验证。这样的问题一直是Discussed before

    【讨论】:

      【解决方案3】:

      您不能简单地下载 HTML 页面并将其保存为 .pdf 以将其转换为 PDF。您必须使用库或某些东西才能将 HTML 页面转换为 PDF。

      它适用于第二个网址,因为它已经是 PDF,因此您可以在下载时保存它。

      【讨论】:

        猜你喜欢
        • 2016-09-11
        • 1970-01-01
        • 2021-08-28
        • 2021-10-18
        • 1970-01-01
        • 2019-02-20
        • 2012-02-03
        • 2014-11-14
        • 1970-01-01
        相关资源
        最近更新 更多