簡體   English   中英

如何使用 iTextSharp 為頁面添加邊框?

[英]How do I add a border to a page using iTextSharp?

是否可以使用iTextSharp為 PDF 文檔中的頁面添加邊框? 我正在從頭開始生成 PDF 文件,因此我不需要為已經存在的文檔添加邊框。

例如,這是我的代碼:

Document pdfDocument = new Document(PageSize.LETTER);
Font headerFont = new Font(baseFont, 13);
Font font = new Font(baseFont, 10);
PdfWriter writer = PdfWriter.GetInstance(pdfDocument, 
                                         new FileStream(fileName, FileMode.Create));
pdfDocument.Open();

//I add IElements here.

pdfDocument.Close();

這是 C# 中的答案(改編自 Mark Storer)。 此示例使用頁面的邊距來繪制邊框,有時我發現這對調試頁面布局很有用。

public override void OnEndPage(PdfWriter writer, Document document)
{
    base.OnEndPage(writer, document);

    var content = writer.DirectContent;
    var pageBorderRect = new Rectangle(document.PageSize);

    pageBorderRect.Left += document.LeftMargin;
    pageBorderRect.Right -= document.RightMargin;
    pageBorderRect.Top -= document.TopMargin;
    pageBorderRect.Bottom += document.BottomMargin;

    content.SetColorStroke(BaseColor.RED);
    content.Rectangle(pageBorderRect.Left, pageBorderRect.Bottom, pageBorderRect.Width, pageBorderRect.Height);
    content.Stroke();
}

我建議您在生成當前頁面時獲取當前頁面的直接內容,並使用PdfContentByte進行邊框。

您可能需要一個PdfPageEventHelper派生的 class 來在 onEndPage 事件中進行繪圖。

您可以通過document參數的getPageSize()查詢當前頁面大小,並使用它(稍微調整一下)來繪制邊框。 鑒於您使用的是 iTextSharp,您可能有一個PageSize屬性而不是“get”方法。

就像是:

public void onEndPage(PdfWriter writer, Document doc) {
  PdfContentByte content = writer.getDirectContent();
  Rectangle pageRect = doc.getPageSize();

  pageRect.setLeft( pageRect.getLeft() + 10 );
  pageRect.setRight( pageRect.getRight() - 10 );
  pageRect.setTop( pageRect.getTop() - 10 );
  pageRect.setBottom( pageRect.getBottom() + 10 );

  content.setColorStroke( Color.red );
  content.rectangle(pageRect.getLeft(), pageRect.getBottom(), pageRect.getWidth(), pageRect.getHeight());
  content.stroke();
}

請注意,您實際上可以將Rectangle傳遞給content.rectangle() ,此時使用該矩形的邊框和填充設置。 我認為這可能有點令人困惑,所以沒有這樣編碼。

PdfContentByte content = pdfwrite1.DirectContent;
            Rectangle rectangle = new Rectangle(doc.PageSize);
            rectangle.Left += doc.LeftMargin;
            rectangle.Right -= doc.RightMargin;
            rectangle.Top -= doc.TopMargin;
            rectangle.Bottom += doc.BottomMargin;
            content.SetColorStroke(BaseColor.BLACK);
            content.Rectangle(rectangle.Left, rectangle.Bottom, rectangle.Width, rectangle.Height);
            content.Stroke();

我能夠為現有的 PDF 添加紅色邊框

public void createPdf(PdfReader  pdfReader)
        throws DocumentException, IOException {
    String userDir = System.getProperty("user.dir");
    System.out.println("userDir = " + userDir);
    RESULT  = userDir + "/work/"+"sample.pdf";
    // step 1
    Document document = new Document();
    // step 2
    PdfCopy copy = new PdfCopy(document, new FileOutputStream(RESULT));

    // step 3
    document.open();
    int noOfPages = pdfReader.getNumberOfPages();
    for (int page = 0; page < noOfPages; ) {
        if(page==0) {
            PdfImportedPage immportedPage = copy.getImportedPage(pdfReader, ++page);
            PageStamp stamp = copy.createPageStamp(immportedPage);
            PdfContentByte canvas = stamp.getOverContent();
            drawPageBorder(canvas, PageSize.A4.getWidth(), PageSize.A4.getHeight());
            stamp.alterContents();
            copy.addPage(immportedPage);
        } else {
            copy.addPage(copy.getImportedPage(pdfReader, ++page));
        }
    }

    copy.freeReader(pdfReader);
    pdfReader.close();
    // step 4
    document.close();
}

public void drawPageBorder(PdfContentByte content, float width, float height) {
    content.saveState();
    PdfGState state = new PdfGState();
    state.setFillOpacity(0.0f);
    content.setGState(state);
    content.setColorStroke(BaseColor.RED);
    content.setLineWidth(6);
    content.rectangle(5, 5, width, height);
    content.fillStroke();
    content.restoreState();
}
protected void GenerateReport(object sender, EventArgs e)
{
    Document document = new Document(PageSize.A4, 88f, 88f, 10f, 10f);
    Font NormalFont = FontFactory.GetFont("Arial", 12, Font.NORMAL, Color.BLACK);
    using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
    {
        PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
        Phrase phrase = null;
        PdfPCell cell = null;
        PdfPTable table = null;
 
        document.Open();
 
        //Header Table
        table = new PdfPTable(1);
        table.TotalWidth = 400f;
        table.LockedWidth = true;
        table.SetWidths(new float[] { 1f });
 
        //Company Name and Address
        phrase = new Phrase();
        phrase.Add(new Chunk("Microsoft Northwind Traders Company\n\n", FontFactory.GetFont("Arial", 16, Font.BOLD, Color.RED)));
        phrase.Add(new Chunk("107, Park site,\n", FontFactory.GetFont("Arial", 8, Font.NORMAL, Color.BLACK)));
        phrase.Add(new Chunk("Salt Lake Road,\n", FontFactory.GetFont("Arial", 8, Font.NORMAL, Color.BLACK)));
        phrase.Add(new Chunk("Seattle, USA", FontFactory.GetFont("Arial", 8, Font.NORMAL, Color.BLACK)));
        cell = PhraseCell(phrase, PdfPCell.ALIGN_LEFT);
        cell.VerticalAlignment = PdfCell.ALIGN_TOP;
        table.AddCell(cell);
 
        document.Add(table);
 
        table = new PdfPTable(2);
        table.HorizontalAlignment = Element.ALIGN_LEFT;
        table.SetWidths(new float[] { 0.3f, 1f });
        table.SpacingBefore = 20f;
 
        //Employee Details
        cell = PhraseCell(new Phrase("Employee Record", FontFactory.GetFont("Arial", 12, Font.UNDERLINE, Color.BLACK)), PdfPCell.ALIGN_CENTER);
        cell.Colspan = 2;
        table.AddCell(cell);
        cell = PhraseCell(new Phrase(), PdfPCell.ALIGN_CENTER);
        cell.Colspan = 2;
        cell.PaddingBottom = 30f;
        table.AddCell(cell);
 
        table = new PdfPTable(2);
        table.SetWidths(new float[] { 0.5f, 2f });
        table.TotalWidth = 340f;
        table.LockedWidth = true;
        table.SpacingBefore = 20f;
        table.HorizontalAlignment = Element.ALIGN_RIGHT;
 
        phrase = new Phrase();
        phrase.Add(new Chunk("Mr. Mudassar Ahmed Khan\n", FontFactory.GetFont("Arial", 10, Font.BOLD, Color.BLACK)));
        phrase.Add(new Chunk("(Moderator)", FontFactory.GetFont("Arial", 8, Font.BOLD, Color.BLACK)));
        cell = PhraseCell(phrase, PdfPCell.ALIGN_LEFT);
        cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
        cell.Colspan = 2;
        table.AddCell(cell);
 
        cell = PhraseCell(new Phrase(" "), PdfPCell.ALIGN_LEFT);
        cell.Colspan = 2;
        table.AddCell(cell);
 
        //Employee Id
        table.AddCell(PhraseCell(new Phrase("Employee code:", FontFactory.GetFont("Arial", 8, Font.BOLD, Color.BLACK)), PdfPCell.ALIGN_LEFT));
        table.AddCell(PhraseCell(new Phrase("0001", FontFactory.GetFont("Arial", 8, Font.NORMAL, Color.BLACK)), PdfPCell.ALIGN_LEFT));
        cell = PhraseCell(new Phrase(), PdfPCell.ALIGN_CENTER);
        cell.Colspan = 2;
        cell.PaddingBottom = 10f;
        table.AddCell(cell);
 
 
        //Address
        table.AddCell(PhraseCell(new Phrase("Address:", FontFactory.GetFont("Arial", 8, Font.BOLD, Color.BLACK)), PdfPCell.ALIGN_LEFT));
        phrase = new Phrase(new Chunk("507 - 20th Ave. E.\nApt. 2A\n", FontFactory.GetFont("Arial", 8, Font.NORMAL, Color.BLACK)));
        phrase.Add(new Chunk("Seattle\n", FontFactory.GetFont("Arial", 8, Font.NORMAL, Color.BLACK)));
        phrase.Add(new Chunk("WA USA 98122", FontFactory.GetFont("Arial", 8, Font.NORMAL, Color.BLACK)));
        table.AddCell(PhraseCell(phrase, PdfPCell.ALIGN_LEFT));
        cell = PhraseCell(new Phrase(), PdfPCell.ALIGN_CENTER);
        cell.Colspan = 2;
        cell.PaddingBottom = 10f;
        table.AddCell(cell);
 
        //Date of Birth
        table.AddCell(PhraseCell(new Phrase("Date of Birth:", FontFactory.GetFont("Arial", 8, Font.BOLD, Color.BLACK)), PdfPCell.ALIGN_LEFT));
        table.AddCell(PhraseCell(new Phrase("25 FEBRUARY", FontFactory.GetFont("Arial", 8, Font.NORMAL, Color.BLACK)), PdfPCell.ALIGN_LEFT));
        cell = PhraseCell(new Phrase(), PdfPCell.ALIGN_CENTER);
        cell.Colspan = 2;
        cell.PaddingBottom = 10f;
        table.AddCell(cell);
        document.Add(table);
 
        //Add border to page
        PdfContentByte content = writer.DirectContent;
        Rectangle rectangle = new Rectangle(document.PageSize);
        rectangle.Left += document.LeftMargin;
        rectangle.Right -= document.RightMargin;
        rectangle.Top -= document.TopMargin;
        rectangle.Bottom += document.BottomMargin;
        content.SetColorStroke(Color.BLACK);
        content.Rectangle(rectangle.Left, rectangle.Bottom, rectangle.Width, rectangle.Height);
        content.Stroke();
 
        document.Close();
        byte[] bytes = memoryStream.ToArray();
        memoryStream.Close();
        Response.Clear();
        Response.ContentType = "application/pdf";
        Response.AddHeader("Content-Disposition", "attachment; filename=Employee.pdf");
        Response.ContentType = "application/pdf";
        Response.Buffer = true;
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.BinaryWrite(bytes);
        Response.End();
        Response.Close();
    }
}
 
private static PdfPCell PhraseCell(Phrase phrase, int align)
{
    PdfPCell cell = new PdfPCell(phrase);
    cell.BorderColor = Color.WHITE;
    cell.VerticalAlignment = PdfCell.ALIGN_TOP;
    cell.HorizontalAlignment = align;
    cell.PaddingBottom = 2f;
    cell.PaddingTop = 0f;
    return cell;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM