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

[html] view plain copy
  1. using iTextSharp.text;  
  2. using iTextSharp.text.pdf;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.IO;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Threading.Tasks;  
  9.   
  10. namespace TxtToPDF  
  11. {  
  12.     class Program  
  13.     {  
  14.         static void Main(string[] args)  
  15.         {  
  16.             //要转换的文件的路径  
  17.             string path = "D:\\txts\\測試.txt";  
  18.             //第一个参数是txt文件物理路径  
  19.             string[] lines = System.IO.File.ReadAllLines(path, Encoding.GetEncoding("utf-8"));  
  20.             //iTextSharp.text.PageSize.A4    自定义页面大小  
  21.             Document doc = new Document(iTextSharp.text.PageSize.A4, 50, 20, 20, 20);  
  22.             PdfWriter pdfwriter =   
  23.                 PdfWriter.GetInstance(doc, new FileStream(path.ToString().Substring(0, path.ToString().Length - 4) + ".pdf", FileMode.Create));  
  24.   
  25.             doc.Open();  
  26.             //创建我的基本字体  
  27.             BaseFont baseFont = BaseFont.CreateFont("c:\\windows\\fonts\\Arial.TTF", "Identity-H", false);  
  28.             //创建字体      字体大小,字体粗細    字体颜色  
  29.             Font font = new Font(baseFont, 11, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);  
  30.   
  31.             Paragraph paragraph;  
  32.             foreach (string line in lines) {  
  33.                 paragraph = new Paragraph(line, font);  
  34.                 doc.Add(paragraph);  
  35.             }  
  36.   
  37.             //关闭文件  
  38.             doc.Close();  
  39.             Console.WriteLine("txt轉換PDF完成!");  
  40.             Console.ReadKey();  
  41.         }  
  42.     }  
  43. }  


运行前的.txt文件:

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

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

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

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

相关文章:

  • 2021-12-20
  • 2021-04-26
  • 2022-12-23
  • 2021-12-28
  • 2022-12-23
  • 2021-12-17
猜你喜欢
  • 2022-02-14
  • 2022-02-09
  • 2021-10-31
  • 2021-10-14
  • 2021-06-20
  • 2022-02-13
相关资源
相似解决方案