Take the 2-minute tour ×

I am converting a .txt to .pdf in c#. This works fine if the .txt file is not blank. if it is, it threw an error of "The document has no pages".

The pdf gets generated but threw an error of "There was an error opening this document. The file is damaged and could not be repaired" when opening a pdf file.

Code is seen below

  public void converttxttoPDF(string sourcePath, string destPath)
            iTextSharp.text.Document document = new iTextSharp.text.Document();
            string filename = Path.GetFileNameWithoutExtension(sourcePath);
            System.IO.StreamReader myFile = new System.IO.StreamReader(sourcePath);
            string myString = myFile.ReadToEnd();
            if (!Directory.Exists(destPath))
            iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(destPath + "\\" + filename + ".pdf", FileMode.CreateNew));
            document.Add(new iTextSharp.text.Paragraph(myString));
        catch (Exception ex)

let me know if any info needed.


share|improve this question
No comments...? :-( –  Romil N Mar 31 '11 at 14:35
Do you really want a blank PDF to get generated? What possible use could that have? Why not check the text file for content first, and throw a messagebox if it's blank? –  MAW74656 Mar 31 '11 at 16:24
@MAW: I understand that it is of no use to generate a blank PDF, but you know the testers, they test everything..LOL :-) –  Romil N Mar 31 '11 at 17:35

2 Answers 2

up vote 1 down vote accepted

You need to add some content to the pdf. So try this:

myString = string.IsNullOrEmpty(myString) ? " " : myString;
document.Add(new iTextSharp.text.Paragraph(myString));
share|improve this answer
Thanks for the comment. but that still threw the same error! :-( –  Romil N Mar 31 '11 at 14:44
@Xor power: What error? This works for me. What version of iTextSharp are you using? –  František Žiačik Mar 31 '11 at 15:30
Btw, maybe you would want to close the writer too. –  František Žiačik Mar 31 '11 at 15:32
@Ziacik: The version of iTextSharp is Your last comment doesn't get into my head. –  Romil N Mar 31 '11 at 17:37
that helped me when done the changes carefully. Thanks much –  Romil N Mar 31 '11 at 18:15

You need to convince iText that there IS something on that page.

Two Methods:

  1. Be explicit. writer.setPageEmpty(false);
  2. Trick it (which is what Darin suggests). writer.getDirectContent().setLiteral(" ");
share|improve this answer

Your Answer


