Servlet return 损坏的“.pdf”文件
Servlet return corrupted '.pdf' file
也许我不了解流,但我有这样的 servlet:
String filename = "test.pdf";
String Str1 = new String("Lorem ipsum dolor sit amet, eos omnes mandamus in, modus voluptua ei mel. Nec et illud facete maluisset, ");
byte[] Str2 = Str1.getBytes();
InputStream inputStream = null;
inputStream = new ByteArrayInputStream(Str2);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bytesRead;
while ( (bytesRead = inputStream.read(buffer)) != -1)
baos.write(buffer, 0, bytesRead);
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
OutputStream os = response.getOutputStream();
baos.writeTo(os);
os.flush();
os.close();
但是当我尝试在保存后打开文件时出现错误:
我查了一下,baos 有字符串 "Lorem ipsum"。我做错了什么?
您不能只将 string
发送为 PDF
并期望它采用 PDF
格式。这与保存扩展名为 pdf
.
的 text
文件相同
您将不得不使用类似 Apache PDFBox
to convert your string to PDF
format. Take a look at their documentation for an example 的库。
也许我不了解流,但我有这样的 servlet:
String filename = "test.pdf";
String Str1 = new String("Lorem ipsum dolor sit amet, eos omnes mandamus in, modus voluptua ei mel. Nec et illud facete maluisset, ");
byte[] Str2 = Str1.getBytes();
InputStream inputStream = null;
inputStream = new ByteArrayInputStream(Str2);
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bytesRead;
while ( (bytesRead = inputStream.read(buffer)) != -1)
baos.write(buffer, 0, bytesRead);
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
OutputStream os = response.getOutputStream();
baos.writeTo(os);
os.flush();
os.close();
但是当我尝试在保存后打开文件时出现错误:
我查了一下,baos 有字符串 "Lorem ipsum"。我做错了什么?
您不能只将 string
发送为 PDF
并期望它采用 PDF
格式。这与保存扩展名为 pdf
.
text
文件相同
您将不得不使用类似 Apache PDFBox
to convert your string to PDF
format. Take a look at their documentation for an example 的库。