简体   繁体   中英

Convert blank .txt file to PDF in C#

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)
    {
        try
        {
            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();
            myFile.Close();
            if (!Directory.Exists(destPath))
                Directory.CreateDirectory(destPath);
            iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(destPath + "\\" + filename + ".pdf", FileMode.CreateNew));
            document.Open();
            document.Add(new iTextSharp.text.Paragraph(myString));
            document.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

let me know if any info needed.

thanks

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

myString = string.IsNullOrEmpty(myString) ? " " : myString;
document.Add(new iTextSharp.text.Paragraph(myString));

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM