0

I've built a program that receives data from a management system and creates a PDF file inside a server folder, the amount of PDFs created by the end of the day are 300 more or less. Those PDFs are created during the day as the users create their orders, once the program creates the PDF the user sends the PDF attached by email to somebody.

My problem is, a random PDF gets corrupted during the day while sending it by email, like only one arrives corrupted in the server.

I've checked the generated PDFs and they aren't corrupted in the creation folder, I've also added a size check before sending it by email and they always have the correct size, the problems happens while sending them.

I've also tried to change the way it was being created and sent, implemented the creation in different ways but nothing worked for me.

Do you guys have any idea of what could cause it? It's strange that it happens to only one of many.

Thanks in advance.

Follow my code below for the PDF generation:

    String sCurrentLine = "";
    Document document = null;
    PdfContentByte cb = null;
    PdfReader reader = null;
    PdfImportedPage page = null;
    Paragraph top = null;
    PdfWriter writer = null;
    BufferedReader bufferReader = null;
    SmbFileOutputStream sfosWritter = null;
    SmbFileInputStream sfosReader = null;
    SmbFile smbFile;
    String[] doc = null;
 //*****************************************************************************************
    
    try{ 
        doc = docs_folder.split("/");
         
        smbFile = Utilities.authentication(docFolder, domain, user, pwd);
        // Creates the pdf file inside the server's folder
        sfosWritter = new SmbFileOutputStream(smbFile);
        // Reads the pdf's template inside the server's folder
        sfosReader = new SmbFileInputStream(Utilities.authentication(templateFolder, 
                domain, user, pwd));
        
        // Creates an empty pdf document
        document = new Document(PageSize.A4);
        
        writer = PdfWriter.getInstance(document, sfosWritter);
        
        document.open();
        
        cb = writer.getDirectContent();            
        reader = new PdfReader(sfosReader);            
        page = writer.getImportedPage(reader, 1);
        
        // Document's configuration
        document.newPage();
        cb.addTemplate(page, par1, par2);
        
        // Do while there are pages to read in the Spool File
        do {
            
            bufferReader = new BufferedReader(new InputStreamReader(spoolFile, charset));
            
            if(bufferReader.ready()) {
                while ((sCurrentLine = bufferReader.readLine()) != null) {
                    
                    top = new Paragraph(floatLeading, sCurrentLine, FontFactory.getFont(FontFactory.COURIER, font));
                    
                    top.setPaddingTop(paddingTop); 
                    
                    document.add(top);
                }                   
                
                document.newPage();
            }
            
        }while(spoolFile.nextPage());
       
        document.close();
        
    }catch (Exception e) {
        e.printStackTrace();
    } finally {

        // closing FileOutputStream
        try {
            if(sfosWritter != null && sfosReader != null) {
                sfosWritter.close();
                sfosReader.close();
            }
        } catch (IOException io) {/*Failed to close*/
            io.printStackTrace();
        }

    }

Sending email code:

    DataSource source = null;
    MimeMessage message;
    MimeBodyPart attachmentBodyPart, textBodyPart;
    MimeMultipart multipart;
    Session session = null;
    Properties properties = null;
    MimeMessage message = null;
    boolean attach = true;
    
    try {
        
        properties = System.getProperties();  
        properties.setProperty("mail.smtp.host", server_ip);
        properties.put("mail.smtp.port", server_port);
        session = Session.getDefaultInstance(properties);
        
        message = new MimeMessage(session);
        message.setHeader("Disposition-Notification-To", from);
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        
        if(!copy.isEmpty())
            message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(copy));
        
        textBodyPart = new MimeBodyPart();
        attachmentBodyPart = new MimeBodyPart();
        multipart = new MimeMultipart();
        
        message.setSubject(subject);
                
        if(attach && !attachmentName.isEmpty()) {
            
            source = new FileDataSource(new StringBuilder(attachmentPath).append(attachmentName).toString());
            
            attachmentBodyPart.setDataHandler(new DataHandler(source));
            attachmentBodyPart.setFileName(attachmentName);
            
            multipart.addBodyPart(attachmentBodyPart);
        }
        
        if(!body.isEmpty()) {
            textBodyPart.setText(body);
            textBodyPart.setContent(body, "text/html");
            multipart.addBodyPart(textBodyPart);
        }
        
        message.setContent(multipart);
        message.saveChanges();
                    
        return message;
    } catch (Exception e) {
        e.printStackTrace();    
    }
Henrique
  • 131
  • 1
  • 6
  • 2
    Do you have any information in which way the PDF file is corrupted? When the corruption issue happens, what is actually received? Random bytes or something that still looks somewhat like a PDF file? Does it start with `%PDF-` and does it end with `%%EOF`? – rhens Apr 22 '21 at 15:17
  • The final user receives a PDF file, but the size is presented in Bytes not in KB. Just to give an example, the last case they've reported the file size was 270 bytes. I've checked the original file and it had the right size written in KB, I was able to open it without any problem. – Henrique Apr 23 '21 at 09:47
  • 1
    Is it simply truncated? Try to open the corrupted file with a text or hex editor to check if it still resembles the start (or a portion) of a PDF file. – rhens Apr 23 '21 at 10:07
  • I've opened it with Notepad++ and it's completely empty, no information inside it. Instead with Adobe it says "not a supported file type or the file has been damaged..". – Henrique Apr 23 '21 at 11:05

1 Answers1

1

We're doing something similar & not surprisingly our code looks similar to yours, but everything is working fine here.

Maybe this difference: we make the Attachment available via a ByteArrayDataSource.

Here's the relevant code from our App:

final DataSource pdfSource       = new ByteArrayDataSource(pdfBuilder.pdfBytes, "application/octet-stream");

final BodyPart   messageBodyPart = new MimeBodyPart();

final BodyPart   pdfBodyPart = new MimeBodyPart();
/**/             pdfBodyPart.setDataHandler(new DataHandler(pdfSource));
/**/             pdfBodyPart.setFileName   ("filename");

final Message    message = new MimeMessage(session);
/**/             message.setContent(new MimeMultipart(messageBodyPart, pdfBodyPart));
Dave The Dane
  • 650
  • 1
  • 7
  • 18
  • Awesome, thanks for your feedback, gonna try it and let you guys know. – Henrique Apr 16 '21 at 10:55
  • Just to give a feedback, it didn't solve my problem unfortunately, still trying to find a solution. Thanks a lot for sharing the info. – Henrique Apr 19 '21 at 08:00
  • 1
    Maybe your file is being corrupted on the way? A virus scanner perhaps? Do you have the possibility to inspect the raw Mime-Encoded data arriving at the recipient? It is possible with Outlook, but very well hidden. With a decent Mail-Client like Thunderbird it's much easier. – Dave The Dane Apr 22 '21 at 08:05
  • The file is being corrupted on the way, cause the original one is correct generated. That's a good tip to inspect the raw Mime-Encoded, gonna find a way to do it. Thanks a lot. – Henrique Apr 23 '21 at 09:59
  • I'm just curious to know if you found a solution to your problem? – Dave The Dane May 11 '21 at 13:49
  • Unfortunately not yet, I'm still trying to solve it, but I guess it's related to latency. I'm gonna give you guys a feedback as soon as I find a solution. Thanks a lot. – Henrique May 27 '21 at 12:08
  • Hello, I would like to update this topic saying the problem was solved, the pdf was crashing in the server side, there was a program that was reading the created pdfs too fast not waiting them to be completele loaded. Thanks for the support. – Henrique Sep 08 '22 at 14:30