【发布时间】:2014-07-29 11:07:38
【问题描述】:
我想使用 PDFsharp 将文本文件转换为 PDF。应该采取什么方法?甚至可能吗?我正在使用 C#.net 开发一个 Web 应用程序
【问题讨论】:
我想使用 PDFsharp 将文本文件转换为 PDF。应该采取什么方法?甚至可能吗?我正在使用 C#.net 开发一个 Web 应用程序
【问题讨论】:
方法是检查 PDFsharp 和 MigraDoc 的示例,然后决定使用哪个工具。
如果文本可能需要的不仅仅是一页,我猜 MigraDoc 将是更好的选择。
【讨论】:
为此我写了一个代码。
最初,我为此使用了 pdfsharp dll,但这对我不起作用,因为 pdfsharp 无法感知分页符,当我编写代码时,我看到只打印了适合第一页的那些。
然后我了解到 Migradoc 确实可以感知分页符并在需要时自动添加新页面。
这是我的带有两个参数的方法:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using MigraDoc.DocumentObjectModel;
using MigraDoc.Rendering;
using System.IO;
void CreatePDFFileFromTxtFile(string textfilefullpath, string pdfsavefullpath)
{
//first read text to end add to a string list.
List<string> textFileLines = new List<string>();
using (StreamReader sr = new StreamReader(textfilefullpath))
{
while (!sr.EndOfStream)
{
textFileLines.Add(sr.ReadLine());
}
}
Document doc = new Document();
Section section = doc.AddSection();
//just font arrangements as you wish
MigraDoc.DocumentObjectModel.Font font = new Font("Times New Roman", 15);
font.Bold = true;
//add each line to pdf
foreach (string line in textFileLines)
{
Paragraph paragraph = section.AddParagraph();
paragraph.AddFormattedText(line,font);
}
//save pdf document
PdfDocumentRenderer renderer = new PdfDocumentRenderer();
renderer.Document = doc;
renderer.RenderDocument();
renderer.Save(pdfsavefullpath);
}
并用输入文本全路径和输出pdf文件全路径调用该方法进行创建。
这行得通。
【讨论】: