Trying to convert plain text file to iTextSharp without losing format

可紊 提交于 2019-12-24 03:52:43

问题


I am trying to convert text files to PDF with iText Sharp. The conversion itself is not a problem however, I am unable to create the PDF file such that it looks exactly the way the text in the text file is aligned.

This is the code I am using:

public void GetPDF(string data)
    {

        using (MemoryStream ms = new MemoryStream())
        {
            Rectangle docSize = new Rectangle(612, 798);
            Document myDocument = new Document(PageSize.A4.Rotate());

            PdfWriter.GetInstance(myDocument, new FileStream
                                         ("MyNewPDF.pdf", FileMode.Create));

            // step 3:  Open the document now using
            myDocument.Open();

            // step 4: Now add some contents to the document
            myDocument.Add(new Paragraph(data));
            myDocument.Close();
        }
    }

Does anybody have a suggestion as to what to do to simply convert a text file into PDF without losing the format of the text file? Any help is appreciated.


回答1:


I suggest to make your PDF file use a mono spaced font like Courier New.




回答2:


A plain text file contains no formatting. When you refer to how the text is aligned, I have to presume you are viewing the text file with a fixed-width or monospace font. Therefore when you convert the text file to PDF, you should specify that a fixed-width/monospace font is used (such as Lucida Console, Courier New, Consolas, etc.)

Next, word wrap is not generally specified in a plain text file. Long paragraphs of text will end with a carriage return/newline character and that's it. The PDF conversion is likely to introduce some word-wrapping at the page boundaries. To control this you will need to select a font size that wraps where you want it, or insert some CR/LF's manually.



来源:https://stackoverflow.com/questions/6988034/trying-to-convert-plain-text-file-to-itextsharp-without-losing-format

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!