将文本从文本文件添加到 PDF 文件[重复]

2024-06-19

这是我的代码:

        using (FileStream msReport = new FileStream(pdfPath, FileMode.Create))
        {
            //step 1
            using (Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 140f, 10f))
            {
                try
                {
                    // step 2.
                    StreamReader sr = new StreamReader("TextFile.txt");
                    string line;
                    PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, msReport);
                    pdfWriter.PageEvent = new ITextEvents();

                    //open the stream 
                    pdfDoc.Open();

                    for (int i = 0; i < 100; i++)
                    {
                        if ((line = sr.ReadLine()) != null)
                        {
                            Paragraph para = new Paragraph(line, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 6));

                            para.Alignment = Element.ALIGN_LEFT;

                            pdfDoc.Add(para);

                            //pdfDoc.NewPage();
                        }
                    }
                    sr.Close();
                    pdfDoc.Close();

它正在工作...它读取我计算机中的文本文件并将其添加到 PDF...问题是 - 它不保留文本文件的格式。它只是添加文本。我需要保持原样。有什么办法可以保持文本的格式吗?我可以以某种方式将其添加到表格中并格式化表格,或者类似的东西吗?


试试这个

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf; 

namespace TxtToPdf
{
    class Program
    {
        static void Main(string[] args)
        {
            //Read the Data from Input File

            StreamReader rdr = new      StreamReader("Path/Test.txt");

           //Create a New instance on Document Class

            Document doc = new Document();

           //Create a New instance of PDFWriter Class for Output File

           PdfWriter.GetInstance(doc, new  FileStream("Path/Test.pdf", FileMode.Create));

           //Open the Document

            doc.Open();

           //Add the content of Text File to PDF File

           doc.Add(new Paragraph(rdr.ReadToEnd()));

           //Close the Document

           doc.Close();


           //Open the Converted PDF File

           System.Diagnostics.Process.Start("Path/Test.pdf");
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将文本从文本文件添加到 PDF 文件[重复] 的相关文章

随机推荐