2016-08-18 53 views
1

使用PDFbox閱讀PDF文件的PDF文件,下面的jave代碼完美地閱讀pdf並存儲在項目位置。PDF閱讀使用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文件

+0

所以,你想知道如何將17個獨立的pdf頁面合併成一個文件? –

+0

@rabbitguy:正好 – Prabu

+0

夥計請求幫助 – Prabu

回答

1

下面是一些代碼,基於PDFMergerExample t帽子在評論中被提及。請注意,我沒有檢查您的網址檢索代碼是否正確。

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); 
    } 
} 
+0

非常感謝我會檢查您的反饋並更新 – Prabu

+0

感謝您的幫助,但我在最後一節中有一個問題,它不清楚正確的來源列表,當我執行第一次計數將是2和第二次執行附加新的頁面計數,所以文檔沒有創建 – Prabu

+0

@Prabu我不明白你的意思;可能是因爲你沒有第二次初始化/清空源ArrayList? (你不能重用它,因爲輸入流將被「消耗」) –