PDF使用PDF框阅读 - 带页数的说明

时间:2016-08-18 14:22:10

标签: java pdfbox pdf-reader

使用PDFbox从网址阅读pdf文件,在jave代码下方,它非常适合阅读pdf并存储在项目位置。

String pdfPageCount = 17;
String pdfUrl = "abc.org/invoicepdf.pdf?Range=1";
URL pdfDownload = new URL(pdfUrl);
connectionGet = (HttpsURLConnection) pdfDownload.openConnection();
String authorizationHeader1 = "Bearer " + getToken;
connectionGet.setRequestProperty("Authorization", authorizationHeader1);
connectionGet.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connectionGet.setRequestMethod("GET");
int responseCode = connectionGet.getResponseCode();
    if (responseCode != 404) {
        PDDocument pd = new PDDocument();
        InputStream inputstreamFinal1 = connectionGet.getInputStream();
        PDDocument load = PDDocument.load(inputstreamFinal1);                        
        load.save("CopyOfInvoice1.pdf");
    }

我的下一步

我想基于pdfPageCount值循环流程,目前我在pdfUrl(/invoicepdf.pdf?Range=1)中将页面数量硬编码为1

预期:

阅读所有17页并保存到单个pdf文件

1 个答案:

答案 0 :(得分:1)

以下是一些代码,基于评论中提到的PDFMergerExample。请注意,我还没有检查您的网址检索代码是否正确。

List<InputStream> sources = new ArrayList<InputStream>();
int pdfPageCount = 17;
try
{
    for (int p = 1; p <= pdfPageCount; ++p)
    {
        String pdfUrl = "abc.org/invoicepdf.pdf?Range=" + p;
        URL pdfDownload = new URL(pdfUrl);
        HttpsURLConnection connectionGet = (HttpsURLConnection) pdfDownload.openConnection();
        String authorizationHeader1 = "Bearer " + getToken;
        connectionGet.setRequestProperty("Authorization", authorizationHeader1);
        connectionGet.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connectionGet.setRequestMethod("GET");
        int responseCode = connectionGet.getResponseCode();
        if (responseCode != 404)
        {
            sources.add(connectionGet.getInputStream());
        }
        else
        {
            //TODO error handling
            return;
        }
    }
    PDFMergerUtility pdfMerger = new PDFMergerUtility();
    pdfMerger.addSources(sources);
    pdfMerger.setDestinationFileName("CopyOfInvoice1.pdf");
    pdfMerger.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
}
catch (IOException e)
{
     //TODO error handling
     return;
}
finally
{
    // cleanup
    for (InputStream source : sources)
    {
        IOUtils.closeQuietly(source);
    }   
}