Itextsharp使用c#动态地将文本写入pdf

时间:2013-06-10 07:53:04

标签: c# itextsharp

我很难用这个,需要大师的帮助!

我正在使用itextsharp来动态写入文本,我不想将其保存到服务器,只需将其放入内存流并以pdf格式显示。

如何修改此代码。

    var reader = new PdfReader(filePath);
    var size = reader.GetPageSizeWithRotation(1);
    var document = new Document(size);

    var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
    var writer = PdfWriter.GetInstance(document, fs);
    document.Open();

    var cb = writer.DirectContent;

    for (int page = 1; page <= reader.NumberOfPages; page++)
    {
        document.NewPage();
        var importedPage = writer.GetImportedPage(reader, page);
        cb.AddTemplate(importedPage, 0, 0);

        BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        cb.BeginText();
        cb.SetFontAndSize(bf, 10);
        cb.ShowTextAligned(Element.ALIGN_LEFT, lefttext, 50, 400, 90);
        cb.EndText();

        cb.BeginText();
        cb.SetFontAndSize(bf, 10);
        cb.ShowTextAligned(Element.ALIGN_JUSTIFIED_ALL, headertext, 280, 720, 0);
        cb.EndText();

        cb.BeginText();
        cb.SetFontAndSize(bf, 10);
        cb.ShowTextAligned(Element.ALIGN_JUSTIFIED_ALL, footertext, 280, 50, 0);
        cb.EndText();
    }

    document.Close();
    fs.Close();
    writer.Close();
    reader.Close();

我修改了我的代码,但这次它将同一页面多次写入第一页。有什么不对?你能帮助这个菜鸟:(

    var reader = new PdfReader(server.MapPath("~/Data/162013.pdf"));
    using (var ms = new MemoryStream())
    {
        var stamper = new PdfStamper(reader, ms);
        var cb = stamper.GetOverContent(1);
        var size = reader.GetPageSizeWithRotation(1);
        var document = new Document(size);
        document.Open();
        for (var page = 1; page <= reader.NumberOfPages; page++)
        {
            document.NewPage();
            var importedPage = stamper.GetImportedPage(reader, page);
            cb.AddTemplate(importedPage, 0 , 0);

            var bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            cb.BeginText();
            cb.SetFontAndSize(bf, 10);
            cb.ShowTextAligned(Element.ALIGN_LEFT, "sdfdsf", 50, 400, 90);
            cb.EndText();

            cb.BeginText();
            cb.SetFontAndSize(bf, 10);
            cb.ShowTextAligned(Element.ALIGN_JUSTIFIED_ALL, "sdfsdfsd", 280, 720, 0);
            cb.EndText();

            cb.BeginText();
            cb.SetFontAndSize(bf, 10);
            cb.ShowTextAligned(Element.ALIGN_JUSTIFIED_ALL, "sdfsdf", 280, 50, 0);
            cb.EndText();
        }

        stamper.FormFlattening = true;
        document.Close();
        stamper.Close();
        DownloadAsPDF(ms);
    }

}

0 个答案:

没有答案