[英]How to write PDF content in a string to a file in java?
我收到包含PDF的服務器的回復。 如下所示(如下所示是簡短的編輯版本):
%PDF-1.4
%????
9 0 obj
%%EOF
使用此字符串或字節數組,如何創建pdf文件?
我已經嘗試使用以下內容,但是它在pdf中顯示空白頁
OutputStream oos = new FileOutputStream("test.pdf");
oos.write(b);
我可以在控制台中看到WholeString,它是一個長字符串,以%PDF-1.4開頭,以%% EOF結尾。 我還嘗試讀取8192字節並寫入。 結果仍然相同:
byte[] buf = wholeString.getBytes(Charset.forName("UTF-8"));
OutputStream oos = new FileOutputStream(tpath);
InputStream is = new ByteArrayInputStream(buf);
int c = 0;
while ((c = is.read(buf, 0, buf.length)) > 0) {
System.out.println();
oos.write(buf, 0, c);
oos.flush();
}
oos.close();
is.close();
我正在使用EntityUtils來獲取流:
String responseBody = EntityUtils.toString(httpResponse.getEntity(), Charset.forName("UTF-8"));
然后將轉換后的字符串發送到另一種方法,在該方法中,我嘗試將其寫入文件。
在評論中進行討論之后,這應該可以解決您的直接問題:
byte[] entityBytes = EntityUtils.toByteArray(httpResponse.getEntity());
Files.write(Paths.get("test.pdf"), entityBytes);
進入程序的所有內容始終以字節為單位。
如果沒有從程序外部獲取字節,則意味着某些框架或庫已經完成了解碼,可能是錯誤的。
請注意,通常應避免轉換為字符串,除非:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.