簡體   English   中英

將Base64圖像轉換為PDF並添加為Java郵件的附件

[英]Base64 Image Conversion to PDF and add as an attachment to java mail

我有一個圖像的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);

%>

如果我做錯了事,請告訴我。 提前致謝。

我做到了。 非常感謝您的建議:)

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();

            DataSource pdfds = new ByteArrayDataSource(baos.toByteArray(), "application/pdf");
            pdfBodyPart.setDataHandler(new DataHandler(pdfds));
            //pngBodyPart.setHeader("Content-ID", "<dashboard>");
            //pngBodyPart.setDisposition(MimeBodyPart.INLINE);
            pdfBodyPart.setFileName("AnnotatedDashboard.pdf");
            multipart.addBodyPart(pdfBodyPart);
            // Send the complete message parts
            message.setContent(multipart);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM