MrM
MrM

Reputation: 22009

Created pdf error message(...file is damaged and could not be repaired)

I created a pdf file and sent in an email message. The email is sent fine but to open the pdf, I keep getting the following error: "There was an error opening this document. The file is damaged and could not be repaired". This is the code. I am not sure what I am doing wrong...

       Document myDoc = new Document(PageSize.LETTER, 20f, 20f, 18f, 20f);

        using (MemoryStream ms = new MemoryStream())
        {
            PdfWriter pWriter = PdfWriter.GetInstance(myDoc, ms);

            myDoc.Open();

            PdfPTable table = new PdfPTable(2);
            table.WidthPercentage = 100;
            table.SpacingAfter = 10;

            float[] widths = new float[] { 1f, 2f };
            table.SetWidths(widths);
            table.HorizontalAlignment = 0;
            table.SpacingBefore = 20f;
            table.SpacingAfter = 30f;

            Font regularFont = new Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12);
            Font boldFont = new Font(iTextSharp.text.Font.FontFamily.HELVETICA, 14, 1);
            Font headerFont = new Font(iTextSharp.text.Font.FontFamily.HELVETICA, 18, 1);

            PdfPCell cell = new PdfPCell();
            cell.BorderWidth = 1;

            cell = new PdfPCell(new Phrase("HEADER", headerFont));
            cell.Colspan = 2;
            cell.HorizontalAlignment = 1; 
            table.AddCell(cell);

            cell.Colspan = 1;
            cell.HorizontalAlignment = 0; 

            cell.Phrase = new Phrase("CONTENT:", boldFont);
            table.AddCell(cell);
            cell.Phrase = new Phrase("content", regularFont);
            table.AddCell(cell);
            myDoc.Add(table);

            MailMessage msg = new MailMessage();

            msg.From = new MailAddress("[email protected]", "CONTENT Report");
            msg.To.Add(new MailAddress("[email protected]"));

            msg.Subject += "Content Report";
            msg.Body += "Message.<br> :)";
            msg.IsBodyHtml = true;

            ms.Position = 0;
            msg.Attachments.Add(new Attachment(ms, "test.pdf", "application/x-pdf"));
            SmtpClient client = new SmtpClient("10.1.1.15");
            client.Send(msg);

Upvotes: 1

Views: 3300

Answers (1)

Mark Storer
Mark Storer

Reputation: 15890

You forgot something important:

 myDoc.Close();

Stick it in right after you make your last change to myDoc.

Upvotes: 5

Related Questions