2014-11-04 29 views
1

我在SD卡中有單頁多個PDF文件。現在我需要以編程方式將這些單頁PDF文件合併到一個PDF文檔中。我已經使用Android PDF Writer庫來創建這些單個PDF文件。我怎麼能做到這一點?我嘗試了一些代碼和問題,但我找不到任何好的答案。 任何人都可以請幫我嗎?我怎麼能結合多個PDF轉換單個PDF在Android?

+0

,如果你能與該庫讀取每個PDF那麼您可以使用相同的庫生成新的pdf,並在其中添加所有頁面。 – 2014-11-04 14:07:08

+0

我試過了,但沒有什麼可以幫助我的。你可以建議其他的圖書館或者一些代碼來幫助我嗎? – Abhi 2014-11-05 07:24:33

+0

發佈一些代碼,讓我知道你到底在執行上述方法時面臨的是什麼 – 2014-11-05 07:29:24

回答

0

我不知道如何爲APW(Android PDF Writer)做到這一點,但您可以將Android上的多個PDF文件與最新的Apache PdfBox Release結合使用。 (目前還沒有最終... ... RC3)

只需添加這依賴於你的build.gradle:

compile 'org.apache.pdfbox:pdfbox:2.0.0-RC3' 

而在異步任務做到這一點:

private File downloadAndCombinePDFs(String urlToPdf1, String urlToPdf2, String urlToPdf3) throws IOException { 

    PDFMergerUtility ut = new PDFMergerUtility(); 
    ut.addSource(NetworkUtils.downloadFile(urlToPdf1, 20)); 
    ut.addSource(NetworkUtils.downloadFile(urlToPdf2, 20)); 
    ut.addSource(NetworkUtils.downloadFile(urlToPdf3, 20)); 

    final File file = new File(getContext().getExternalCacheDir(), System.currentTimeMillis() + ".pdf"); 

    final FileOutputStream fileOutputStream = new FileOutputStream(file); 
    try { 
     ut.setDestinationStream(fileOutputStream); 
     ut.mergeDocuments(MemoryUsageSetting.setupTempFileOnly()); 

    } finally { 
     fileOutputStream.close(); 
    } 
    return file; 
} 

這裏NetworkUtils.downloadFile()應該返回一個InputStream。 如果你在你的SD卡上有它們,你可以打開一個FileInputStream。

我從網上下載PDF文件是這樣的:

public static InputStream downloadFileThrowing(String url, int timeOutInSeconds) throws IOException { 

    OkHttpClient client = new OkHttpClient(); 
    client.setConnectTimeout(timeOutInSeconds, TimeUnit.SECONDS); 
    client.setReadTimeout(timeOutInSeconds, TimeUnit.SECONDS); 

    Request request = new Request.Builder().url(url).build(); 

    Response response = client.newCall(request).execute(); 
    if (!response.isSuccessful()) 
     throw new IOException("Download not successful.response:" + response); 
    else 
     return response.body().byteStream(); 
} 

要使用OkHttpClient添加到您的build.gradle:

compile 'com.squareup.okhttp:okhttp:2.7.2'