【发布时间】:2015-10-21 17:20:51
【问题描述】:
我有一个图像的 base64 代码,现在的要求是使用 base64 创建一个包含图像的 PDF(使用 base64 代码)并将其作为电子邮件附件附加,而不将其保存在任何物理位置。 这是我到目前为止所尝试的,我将 pdf 作为附件,但说它已损坏。
<%
String b64Image=request.getParameter("img_val");
b64Image = b64Image.replace("data:image/png;base64,", "");
b64Image = b64Image.replace(" ", "+");
/*setting all the email properties
.....
.....
*/
BufferedImage image = ImageIO.read(new ByteArrayInputStream(decodedBytes));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Document document = new Document(PageSize.A4, 10, 10, 10, 10);
PdfWriter.getInstance(document, baos);
document.open();
Image image = Image.getInstance(decodedBytes);
image.scalePercent(50);
document.add(image);
document.close();
/*after this how to add as email attachment iwas not sure so tried with below code*/
/*with the below code im getting attachment, when i open pdf it is saying as corrupted*/
byte[] decoded = org.apache.commons.codec.binary.Base64.decodeBase64(b64Image.getBytes());
pdfBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(decoded, "application/pdf")));
pdfBodyPart.setFileName("Report.pdf");
pdfBodyPart.setDisposition(MimeBodyPart.ATTACHMENT);
multipart.addBodyPart(pdfBodyPart);
message.setContent(multipart);
%>
如果我做错了什么,请告诉我。 提前致谢。
【问题讨论】:
-
首先尝试创建 PDF 并将其写入文件。那个PDF损坏了吗?
decodedBytes值是如何计算的?您知道 PDF 支持 Base64 图像和 PNG,不是吗? iText 需要解码的 PNG 并将其转换为压缩位图。另外:为什么不创建一个与图像大小相同的页面?现在,您创建了一个 A4 页面并将图像缩放到其原始大小的 50%(以像素为单位)(其中像素被视为点),但您不知道图像是否适合具有 10 个点边距的 A4 页面。这一切都很奇怪。 -
这段代码很奇怪,您将图像添加到 pdf(变量
document)但在 PDF 之后使用b64Image?您可能应该使用baos -
创建和写入它工作正常@BrunoLowagie,当我尝试不使用任何文件时,我得到了损坏的文件。 Reg decodedBytes 更新了问题,我不知道 PNG 或 Base64 的兼容性,图像的大小大于横向,这就是我在 A4 内缩放它的原因。你能给我更多的线索,我可以解决这个问题。谢谢你:)
-
我尝试了两种方法,将图像转换为 pdf,我不确定如何在不保存的情况下将其添加为电子邮件附件,所以我尝试了第二个选项。我在评论部分提到了这一点,指导我使用任何一种方法,我可以将 pdf 添加为附件而不保存它。谢谢@RC。
-
你明白@RC 说什么了吗?您正在创建一个完美的
baos,但您没有使用存储在baos中的字节。相反,您使用的是b64Image.getBytes()。您需要使用baos中存储的字节将 PDF 添加为附件,而不是添加图像字节。
标签: java pdf base64 itext jakarta-mail