使用iTextSharp创建多页PDF

3
我正在尝试使用iTextSharp创建具有多个页面的pdf。
Document document = new Document(PageSize.A4, 2, 2, 10, 10);
private PdfContentByte _pcb;

try
{
    PdfWriter writer = PdfWriter.GetInstance(document, output);
    document.Open();             
    document.NewPage();
    _pcb = writer.DirectContent;
    _pcb.BeginText();
    _pcb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, text, x, y, 0);
    _pcb.EndText();
    writer.Flush();
}
catch(e)
{

}
finally
{
    document.Close();
}

对我来说这个工作很好。但当我试图在同一文档上添加新页面时,它会用新页面替换现有的文本,而没有添加新页面。以下是无法正常工作的代码。

_pcb.EndText();
writer.Flush();
document.NewPage();
_pcb = writer.DirectContent;
_pcb.BeginText();
_pcb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, text, x, y, 0);
_pcb.EndText();
writer.Flush();

在清空第一页文本之后,我正在尝试向文档添加新页面。 - amesh
3个回答

9
以下是我整理和统一您的代码的尝试。通常情况下,避免使用try-catch,除非你真的需要,否则你经常会错过一些非常重要的错误。(例如,你没有设置必需的字体和大小,但也许你只是省略了那段代码。)此外,除非你正在编写一个非常大的PDF,否则没有必要刷新缓冲区,让操作系统在必要时为你完成这项工作。
当我运行下面的代码时,我得到了两页文本,您是否也可以得到相同的结果?(针对iTextSharp 5.2.0.0版本)
        var output = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Output.pdf");
        var bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
        using (FileStream fs = new FileStream(output, FileMode.Create, FileAccess.Write, FileShare.None)) {
            using (Document doc = new Document(PageSize.A4, 2, 2, 10, 10)) {
                PdfContentByte _pcb;
                using (PdfWriter writer = PdfWriter.GetInstance(doc, fs)) {
                    //Open document for writing
                    doc.Open();
                    //Insert page
                    doc.NewPage();
                    //Alias to DirectContent
                    _pcb = writer.DirectContent;
                    //Set the font and size
                    _pcb.SetFontAndSize(bf, 12);
                    //Show some text
                    _pcb.BeginText();
                    _pcb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Page 1", 40, 600, 0);
                    _pcb.EndText();
                    //Insert a new page
                    doc.NewPage();
                    //Re-set font and size
                    _pcb.SetFontAndSize(bf, 12);
                    //Show more text on page 2
                    _pcb.BeginText();
                    _pcb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Page 2", 100, 400, 0);
                    _pcb.EndText();
                    doc.Close();
                }
            }
        }

我找到了问题所在。在使用_pcb.BeginText()时,我没有使用_pcb.EndText,也没有在写入文本之前设置字体..谢谢.. - amesh

5
你为什么要使用DirectContent呢?如果你只是想从头开始创建PDF,只需向Document添加内容即可。
try
{
    iTextSharp.text.Document doc = new iTextSharp.text.Document();
    PdfWriter.GetInstance(doc, new FileStream("HelloWorld.pdf", FileMode.Create));
    doc.Open();
    doc.Add(new Paragraph("Hello World!"));
    doc.NewPage();
    doc.Add(new Paragraph("Hello World on a new page!"));
}
catch (Exception ex)
{

}
finally 
{
    doc.Close();
}

谢谢Alexis。在这里,我根据坐标位置渲染文本。如何使用PdfContentByte来实现,并且应该在什么时候刷新文本?是在完成整个文档后还是每一页都要刷新? - amesh
请告诉我是否有其他方法可以在基于坐标的系统上打印文本。 - amesh
使用ColumnText在绝对位置放置文本。请查看此示例。尽管是用Java编写的,但适应C#应该相当容易。 - Alexis Pigeon

0
以下代码正常运行。
string str = "Page1Page1Page1Page1Page1Page1Page1Page1Page1Page1";
string str2 = "Page2Page2Page2Page2Page2Page2Page2Page2Page2Page2";
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
using (var htmlWorker = new HTMLWokExtend(pdfDoc))
{
    using (var sr = new StringReader(str))
    {
        htmlWorker.Parse(sr);
    }
}
pdfDoc.NewPage();
using (var htmlWorker = new HTMLWokExtend(pdfDoc))
{
    using (var sr = new StringReader(str2))
    {
      htmlWorker.Parse(sr);
    }
}
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;" +
                               "filename=Proforma_Invoice.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();

您可以使用以下函数从HTML正文中填充字符串

private string populatebody()
{
    string body="";
    using (StreamReader reader = new StreamReader(Server.MapPath("~/Dir/Page.html")))
    {
        body = reader.ReadToEnd();
    }
    body = body.Replace("{Content in htmlpage}", "Your Content");
    return body
}

然后在上面的代码中将此主体返回为字符串。 您可以根据需要操作此代码。

以下是HTMLWokExtend类:

public class HTMLWokExtend : HTMLWorker
{
    LineSeparator line = new LineSeparator(1f, 90f, BaseColor.GRAY, Element.ALIGN_CENTER, -12);
    public HTMLWokExtend(IDocListener document) : base(document)
    {

    }
    public override void StartElement(string tag, IDictionary<string, string> str)
    {
        if (tag.Equals("hrline"))
            document.Add(new Chunk(line));
        else
            base.StartElement(tag, str);
    }
}

这个 HTMLWokExtend 是什么? - mkl
谢谢询问。我忘记分享这个类了。还有一件事,您需要在必要的地方添加itextsharp dll引用。 - Singh T

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接