这是我的代码:
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 ...问题是 - 它不保留文本文件的格式。它只是添加了文字。而且我需要保持原样。有没有办法保持文本的格式?我可以以某种方式将它添加到表格并格式化表格,或类似的东西?
答案 0 :(得分:2)
试试这个
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");
}
}
}
答案 1 :(得分:0)
您可以通过读取转义序列来完成此操作,就像更改行时一样,您应该将其读取为\ n,然后将其与PDF一起写入文本。