C#实现将TXT文件转换为PDF文件

下面是.txt文件转换成.pdf文件的主要代码:

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

namespace TxtToPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            //要转换的文件的路径
            string path = "D:\\txts\\測試.txt";
            //第一个参数是txt文件物理路径
            string[] lines = System.IO.File.ReadAllLines(path, Encoding.GetEncoding("utf-8"));
            //iTextSharp.text.PageSize.A4    自定义页面大小
            Document doc = new Document(iTextSharp.text.PageSize.A4, 50, 20, 20, 20);
            PdfWriter pdfwriter = 
                PdfWriter.GetInstance(doc, new FileStream(path.ToString().Substring(0, path.ToString().Length - 4) + ".pdf", FileMode.Create));

            doc.Open();
            //创建我的基本字体
            BaseFont baseFont = BaseFont.CreateFont("c:\\windows\\fonts\\Arial.TTF", "Identity-H", false);
            //创建字体      字体大小,字体粗細    字体颜色
            Font font = new Font(baseFont, 11, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

            Paragraph paragraph;
            foreach (string line in lines) {
                paragraph = new Paragraph(line, font);
                doc.Add(paragraph);
            }

            //关闭文件
            doc.Close();
            Console.WriteLine("txt轉換PDF完成!");
            Console.ReadKey();
        }
    }
}


运行前的.txt文件:

运行后,生成了.pdf文件:



猜你喜欢

转载自blog.csdn.net/m0_37954004/article/details/80109654
今日推荐