【发布时间】:2020-03-11 19:05:53
【问题描述】:
我正在制作一个小程序,它只需要一个 .txt 文件并将其转换为 PDF,我希望 PDF 看起来类似于我使用 Microsoft 的 Print to PDF 时文本文件的外观。我已经很接近了,但是当一行文本超过页面的宽度时,它会换行到新行,并且换行的文本与其上方的文本重叠。如何让换行的文本表现得好像我正在向文档中添加一个新段落而不将换行的文本拆分为一个新段落?
这是我的旧代码:
string dest = @"..\TXT2PDF\Test.pdf";
string source = @"..\TXT2PDF\test2.txt";
string fpath = @"..\TXT2PDF\consola.ttf";
string line;
FileInfo destFile = new FileInfo(dest);
destFile.Directory.Create();
PdfWriter writer = new PdfWriter(dest);
PdfDocument pdf = new PdfDocument(writer);
PageSize ps = new PageSize(612, 792);
pdf.SetDefaultPageSize(ps);
Document document = new Document(pdf);
PdfFont font = PdfFontFactory.CreateFont(fpath);
StreamReader file = new StreamReader(source);
Console.WriteLine("Beginning Conversion");
document.SetLeftMargin(54);
document.SetRightMargin(54);
document.SetTopMargin(72);
document.SetBottomMargin(72);
while ((line = file.ReadLine()) != null)
{
Paragraph p = new Paragraph();
p.SetFixedLeading(4.8f);
p.SetFont(font).SetFontSize(10.8f);
p.SetPaddingTop(4.8f);
p.Add("\u00A0");
p.Add(line);
document.Add(p);
}
document.Close();
file.Close();
Console.WriteLine("Conversion Finished");
Console.ReadLine();
这是我的新代码:
string dest = @"..\TXT2PDF\Test.pdf";
string source = @"..\TXT2PDF\test2.txt";
string fpath = @"..\TXT2PDF\consola.ttf";
string line;
FileInfo destFile = new FileInfo(dest);
destFile.Directory.Create();
PdfWriter writer = new PdfWriter(dest);
PdfDocument pdf = new PdfDocument(writer);
PageSize ps = new PageSize(612, 792);
pdf.SetDefaultPageSize(ps);
Document document = new Document(pdf);
PdfFont font = PdfFontFactory.CreateFont(fpath, "cp1250", true);
StreamReader file = new StreamReader(source);
Console.WriteLine("Beginning Conversion");
document.SetLeftMargin(54);
document.SetRightMargin(54);
document.SetTopMargin(68);
document.SetBottomMargin(72);
document.SetProperty(Property.LEADING, new Leading(Leading.MULTIPLIED, 1.018f));
Paragraph p = new Paragraph();
p.SetFont(font).SetFontSize(10.8f);
p.SetCharacterSpacing(0.065f);
string nl = "";
while ((line = file.ReadLine()) != null)
{
Text t = new Text(nl + "\u0000" + line);
p.Add(t);
nl = "\n";
}
document.Add(p);
document.Close();
file.Close();
Console.WriteLine("Conversion Finished");
Console.ReadLine();
编辑
根据 mkl 的建议,我将 p.SetFixedLeading(4.8f) 替换为 document.SetProperty(Property.LEADING, new Leading(Leading.MULTIPLIED, 1.018f))。这解决了换行文本的间距问题,但它导致段落之间的间距增加得比我想要的要多。为了解决这个问题,我决定只使用一个段落对象并将每一行作为一个新的文本对象添加到段落中。我以前试过一次,但文本对象没有换行。我必须将换行符添加到每个文本对象的开头,以便它们在自己的行上。
【问题讨论】:
-
您使用的前导小于字体大小。这会使线条重叠。
-
@mkl 感谢您的主要解释!我已经修改了我的代码,现在它达到了我想要的间距。感谢您的帮助!