使用itextsharp绘制实线

时间:2017-05-16 07:49:02

标签: html css model-view-controller itext wkhtmltopdf

为了从HTML转换为PDF我使用wkhtmltopdf因为css支持..但我想绘制pdf页面的完整行宽..我使用了HRDIV但由于我将参数传递为args+= "--margin-top 10mm --margin-bottom 10mm --margin-right 3mm --margin-left 3mm ";,因此我可以在b之前和之后留下一些余量..所以我使用ITextsharp来做这个..但是它不会画线 我试过下面的代码:

        PdfContentByte cb;
        // DO PAGE NUMBER
        byte[] bytes1 = System.IO.File.ReadAllBytes(@"E:\temp\test_QA.pdf");
        var FontColour = new BaseColor(97, 123, 149);
        iTextSharp.text.Font baseFontNormal = FontFactory.GetFont("Calibri", 9, iTextSharp.text.Font.NORMAL, FontColour);
        using (MemoryStream stream = new MemoryStream())
        {
            PdfReader reader = new PdfReader(bytes1);
            var doc = new iTextSharp.text.Document();
            PdfWriter writer = PdfWriter.GetInstance(doc, stream);
            writer.PageEvent = new iTextEvents();
            //Open the document for writing                                                
            doc.Open();
            cb = writer.DirectContent;
            using (PdfStamper stamper = new PdfStamper(reader, stream))
            {
                cb.MoveTo(0, doc.PageSize.Height - 55);
                cb.LineTo(doc.PageSize.Width, doc.PageSize.Height - 55);
                cb.SetColorStroke(FontColour);
                cb.Stroke();

                //Move the pointer and draw line to separate footer section from rest of page
                cb.MoveTo(0, doc.PageSize.GetBottom(150));
                cb.LineTo(doc.PageSize.Width, doc.PageSize.GetBottom(55));
                cb.SetColorStroke(FontColour);
                cb.Stroke();
            }
            bytes1 = stream.ToArray();
            System.IO.File.WriteAllBytes(@"E:\download.pdf", bytes1);
            //doc.Close();
        }

知道这里缺少什么吗?

1 个答案:

答案 0 :(得分:0)

您同时使用Document / PdfWriter对(创建新PDF)和PdfReader / PdfStamper对(操纵现有PDF)写入相同的流!除了垃圾,你不应该期望生产任何东西。而是仅使用PdfReader / PdfStamper对,并更改其OverContent

此外,您的代码以另一种方式出错:首先创建路径(cb.MoveTocb.LineTo),然后设置颜色(cb.SetColorStroke),然后尝试使用路径(cb.Stroke)。这会根据PDF规范创建无效内容:创建和使用路径之间不应有其他说明。

因此,使用类似的东西(未经测试,只是在编辑器中更改了代码):

var FontColour = new BaseColor(97, 123, 149);
using (MemoryStream stream = new MemoryStream())
{
    using (PdfReader reader = new PdfReader(@"E:\temp\test_QA.pdf"))
    using (PdfStamper stamper = new PdfStamper(reader, stream))
    {
        Rectangle rect = reader.GetPageSize(1);
        PdfContentByte cb = stamper.GetOverContent(1);
        cb.SetColorStroke(FontColour);
        cb.MoveTo(0, rect.Height - 55);
        cb.LineTo(rect.Width, rect.Height - 55);
        cb.MoveTo(0, rect.GetBottom(150));
        cb.LineTo(rect.Width, rect.GetBottom(55));
        cb.Stroke();
    }
    System.IO.File.WriteAllBytes(@"E:\download.pdf", stream.ToArray());
}