c# - 将文本从文本文件添加到 PDF 文件

标签 c# .net pdf itext

这是我的代码:

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

关于c# - 将文本从文本文件添加到 PDF 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38782784/

相关文章:

ruby-on-rails - 在 Ruby/Rails 中生成 PDF/HTML/DOCX 的最佳方法是什么

php - 如何使用 Zend Framework 生成 _with_ utf-8 多字节字符的 pdf 文件

c# - 从静态类中选择一个随机静态变量

C# - 阻止文件夹在处理时被更改

c# - 企业库 6 Microsoft.Practices.EnterpriseLibrary.Caching 丢失?

c# - 加载程序集及其依赖项

pdf - ImageMagick 或 GhostScript : convert a multi-page TIFF to a multi-page PDF

C# WinForms - 如何制作锁定主窗体的窗体

c# - 从字符串中提取 MAC 地址

c# - 为特定区域创建 S3 存储桶