无法使用itext 7创建文档边框

时间:2018-10-02 14:52:31

标签: itext7

使用下面的代码,我尝试在文档周围设置边框,但未显示任何内容:

           PdfWriter pdfWriter = new PdfWriter(toFile);
            PdfDocument pdfDoc = new PdfDocument(pdfWriter);        //Initialize PDF document
            var pageSize = PageSize.LETTER;
            var document = new iText.Layout.Document(pdfDoc, pageSize);       // Initialize document

            var fontTimesRoman = PdfFontFactory.CreateFont(iText.IO.Font.Constants.StandardFonts.TIMES_ROMAN);
            var fontTimesRomanBold = PdfFontFactory.CreateFont(iText.IO.Font.Constants.StandardFonts.TIMES_BOLD);
            var navy = new DeviceRgb(0, 0, 128);
            var red = new DeviceRgb(139, 0, 0);

            document.SetBorder(new SolidBorder(red, 18));

            document.Add( new Paragraph(DateTime.Now.ToString("MMMM dd, yyyy"))
                            .SetFont(fontTimesRoman)
                            .SetTextAlignment(iText.Layout.Properties.TextAlignment.RIGHT)
                            //.SetHorizontalAlignment(iText.Layout.Properties.HorizontalAlignment.RIGHT)
                            .SetFontSize(11)
                        );

1 个答案:

答案 0 :(得分:1)

这将不起作用,因为文档是页面的大小,并且边框将在页面外部。 如果要在文档的边缘添加边框,则需要在PdfCanvas对象中添加边框

pdfDoc.AddNewPage();
var canvas = new PdfCanvas(pdfDoc, 1);
canvas.SetStokeColor(red);
canvas.SetLineWidth(18f);
canvas.Rectangle(0,1,pageSize.GetWidth()-1,pageSize.GetHeight()-1);
canvas.Stroke();

也不要忘记运行

pdfDoc.Close();