如何使用 PDFsharp 创建 table?

How to create a table using PDFsharp?

刚开始使用 PDFsharp,它工作正常,但现在我想在我的 PDF 中创建表格,但尝试了其他来源,但一无所获。

到目前为止我知道如何使用graph.drawString()

使用 PDFsharp:绘制文本,在其周围画线。

使用 MigraDoc(您已经添加了该标签):将 Table 添加到您的文档并添加您需要的列、行和边框。

MigraDoc 附带的 MigraDoc 示例都是 C#,但可以在论坛上找到 VB.NET 示例。

VB.NET 官方 PDFsharp/MigraDoc 论坛上的示例:
http://forum.pdfsharp.net/viewtopic.php?f=8&t=3207

官方网站上显示表用法的 C# 示例:
http://pdfsharp.net/wiki/Invoice-sample.ashx

我找不到任何清晰简单的基本 table 模板示例。 pdfSharp 是一个非常强大但级别极低的库,因此很难绘制具有固定位置的矩形和文本。无论如何,这里有一个完整的小例子,展示了如何绘制 table:

protected void ExportGraf_Click(object sender, EventArgs e)
{
    PdfDocument document = new PdfDocument();
    document.Info.Title = "Table Example";

    for (int p=0; p<1; p++) 
    { 
        // Page Options
        PdfPage pdfPage = document.AddPage();
        pdfPage.Height = 842;//842
        pdfPage.Width = 590;

        // Get an XGraphics object for drawing
        XGraphics graph = XGraphics.FromPdfPage(pdfPage);

        // Text format
        XStringFormat format = new XStringFormat();
        format.LineAlignment = XLineAlignment.Near;
        format.Alignment = XStringAlignment.Near;
        var tf = new XTextFormatter(graph);
           
        XFont fontParagraph = new XFont("Verdana", 8, XFontStyle.Regular);

        // Row elements
        int el1_width = 80;
        int el2_width = 380;

        // page structure options
        double lineHeight = 20;
        int marginLeft = 20;
        int marginTop = 20;
           
        int el_height = 30;
        int rect_height = 17;

        int interLine_X_1 = 2;
        int interLine_X_2 = 2 * interLine_X_1;

        int offSetX_1 = el1_width;
        int offSetX_2 = el1_width + el2_width;

        XSolidBrush rect_style1 = new XSolidBrush(XColors.LightGray);
        XSolidBrush rect_style2 = new XSolidBrush(XColors.DarkGreen);
        XSolidBrush rect_style3= new XSolidBrush(XColors.Red);

        for (int i = 0; i < 30; i++)
        {
            double dist_Y = lineHeight * (i + 1);
            double dist_Y2 = dist_Y - 2;

            // header della G
            if (i == 0)
            {
                graph.DrawRectangle(rect_style2, marginLeft, marginTop, pdfPage.Width-2* marginLeft, rect_height);

                tf.DrawString("column1", fontParagraph, XBrushes.White,
                              new XRect(marginLeft, marginTop, el1_width, el_height), format);

                tf.DrawString("column2", fontParagraph, XBrushes.White,
                              new XRect(marginLeft + offSetX_1 + interLine_X_1, marginTop , el2_width, el_height), format);

                tf.DrawString("column3", fontParagraph, XBrushes.White,
                              new XRect(marginLeft + offSetX_2 + 2 * interLine_X_2, marginTop, el1_width, el_height), format);

                // stampo il primo elemento insieme all'header
                graph.DrawRectangle(rect_style1, marginLeft, dist_Y2 + marginTop, el1_width, rect_height);
                tf.DrawString("text1", fontParagraph, XBrushes.Black,
                              new XRect(marginLeft, dist_Y + marginTop, el1_width, el_height), format);

                //ELEMENT 2 - BIG 380
                            graph.DrawRectangle(rect_style1, marginLeft + offSetX_1 + interLine_X_1, dist_Y2 + marginTop, el2_width, rect_height);
                            tf.DrawString(
                                "text2",
                                fontParagraph,
                                XBrushes.Black,
                                new XRect(marginLeft + offSetX_1 + interLine_X_1, dist_Y + marginTop, el2_width, el_height),
                                format);


                            //ELEMENT 3 - SMALL 80

                            graph.DrawRectangle(rect_style1, marginLeft + offSetX_2 + interLine_X_2, dist_Y2 + marginTop, el1_width, rect_height);
                            tf.DrawString(
                                "text3",
                                fontParagraph,
                                XBrushes.Black,
                                new XRect(marginLeft + offSetX_2 + 2 * interLine_X_2, dist_Y + marginTop, el1_width, el_height),
                                format);
              

                    }
                        else { 

                        //if (i % 2 == 1)
                        //{
                        //  graph.DrawRectangle(TextBackgroundBrush, marginLeft, lineY - 2 + marginTop, pdfPage.Width - marginLeft - marginRight, lineHeight - 2);
                        //}

                        //ELEMENT 1 - SMALL 80
                        graph.DrawRectangle(rect_style1,  marginLeft, marginTop + dist_Y2, el1_width, rect_height);
                        tf.DrawString(
                
                            "text1",
                            fontParagraph,
                            XBrushes.Black,
                            new XRect(marginLeft, marginTop + dist_Y, el1_width, el_height),            
                            format);

                        //ELEMENT 2 - BIG 380
                        graph.DrawRectangle(rect_style1, marginLeft + offSetX_1 + interLine_X_1 , dist_Y2 + marginTop, el2_width, rect_height);
                        tf.DrawString(
                            "text2",
                            fontParagraph,
                            XBrushes.Black,
                            new XRect(marginLeft + offSetX_1 + interLine_X_1, marginTop + dist_Y, el2_width, el_height),
                            format);


                        //ELEMENT 3 - SMALL 80
         
                        graph.DrawRectangle(rect_style1, marginLeft + offSetX_2 + interLine_X_2, dist_Y2 + marginTop, el1_width, rect_height);
                        tf.DrawString(
                            "text3",
                            fontParagraph,
                            XBrushes.Black,
                            new XRect(marginLeft + offSetX_2 + 2 *interLine_X_2, marginTop + dist_Y, el1_width, el_height),
                            format);

                        }

                    }


            }


            const string filename = "C:\Users\Desktop\test\HelloWorld.pdf";
            document.Save(filename);

            //byte[] bytes = null;
            //using (MemoryStream stream = new MemoryStream())
            //{
            //    document.Save(stream, true);
            //    bytes = stream.ToArray();
            //}

            //SendFileToResponse(bytes, "HelloWorld_test.pdf");

        }

请注意,您可以在文档中打印更多页面;只需更改第一个“for”。

它应该像这样呈现: .

这个工作示例,使用 MigroDoc。我改变了一点 example

    static Table table;
    static Document document;
    static TextFrame addressFrame;
   
    public static void Main()
    {
       
        const PdfFontEmbedding embedding = PdfFontEmbedding.Always;
        PdfDocumentRenderer render = new PdfDocumentRenderer(true, embedding);
        Document doc = CreateDocument();
        render.Document = doc;
        render.DocumentRenderer = render.DocumentRenderer;
        render.RenderDocument();
        render.PdfDocument.Save(@"D:\PDF1.pdf");
        Process.Start(@"D:\PDF1.pdf");
    }

    public static Document CreateDocument()
    {
        // Create a new MigraDoc document
        document = new Document();
        document.Info.Title = "A sample invoice";
        document.Info.Subject = "Demonstrates how to create an invoice.";
        document.Info.Author = "Stefan Lange";

        DefineStyles();

        CreatePage();

        FillContent();

        return document;
    }

    static void DefineStyles()
    {
        // Get the predefined style Normal.
        Style style = document.Styles["Normal"];
        // Because all styles are derived from Normal, the next line changes the 
        // font of the whole document. Or, more exactly, it changes the font of
        // all styles and paragraphs that do not redefine the font.
        style.Font.Name = "Arial";

        style = document.Styles[StyleNames.Header];
        style.ParagraphFormat.AddTabStop("16cm", TabAlignment.Right);

        style = document.Styles[StyleNames.Footer];
        style.ParagraphFormat.AddTabStop("8cm", TabAlignment.Center);

        // Create a new style called Table based on style Normal
        style = document.Styles.AddStyle("Table", "Normal");
        style.Font.Name = "Arial";
        style.Font.Size = 9;

        // Create a new style called Reference based on style Normal
        style = document.Styles.AddStyle("Reference", "Normal");
        style.ParagraphFormat.SpaceBefore = "5mm";
        style.ParagraphFormat.SpaceAfter = "5mm";
        style.ParagraphFormat.TabStops.AddTabStop("16cm", TabAlignment.Right);
    }

    static void CreatePage()
    {
        Section section = document.AddSection();
        
        
        // Create footer
        Paragraph paragraph = section.Footers.Primary.AddParagraph();
        paragraph.AddText("PowerBooks Inc · Sample Street 42 · 56789 Cologne · Germany");
        paragraph.Format.Font.Size = 9;
        paragraph.Format.Alignment = ParagraphAlignment.Center;

        // Create the text frame for the address
        addressFrame = section.AddTextFrame();
        addressFrame.Height = "3.0cm";
        addressFrame.Width = "7.0cm";
        addressFrame.Left = ShapePosition.Left;
        addressFrame.RelativeHorizontal = RelativeHorizontal.Margin;
        addressFrame.Top = "5.0cm";
        addressFrame.RelativeVertical = RelativeVertical.Page;

        // Put sender in address frame
        paragraph = addressFrame.AddParagraph("PowerBooks Inc · Sample Street 42 · 56789 Cologne");
        paragraph.Format.Font.Name = "Arial";
        paragraph.Format.Font.Size = 7;
        paragraph.Format.SpaceAfter = 3;
        
        
        
        // Add the print date field
        paragraph = section.AddParagraph();
        paragraph.Format.SpaceBefore = "8cm";
        paragraph.Style = "Reference";
        paragraph.AddFormattedText("INVOICE");
        paragraph.AddTab();
        paragraph.AddText("Hello World");
        paragraph.AddDateField("dd.MM.yyyy");

        // Create the item table
        table = section.AddTable();
        table.Style = "Table";
        table.Borders.Color = Colors.Black;
        table.Borders.Width = 0.25;
        table.Borders.Left.Width = 0.5;
        table.Borders.Right.Width = 0.5;
        table.Rows.LeftIndent = 0;

        // Before you can add a row, you must define the columns
        Column column = table.AddColumn("1cm");
        column.Format.Alignment = ParagraphAlignment.Center;

        column = table.AddColumn("2.5cm");
        column.Format.Alignment = ParagraphAlignment.Right;

        column = table.AddColumn("3cm");
        column.Format.Alignment = ParagraphAlignment.Right;

        column = table.AddColumn("3.5cm");
        column.Format.Alignment = ParagraphAlignment.Right;

        column = table.AddColumn("2cm");
        column.Format.Alignment = ParagraphAlignment.Center;

        column = table.AddColumn("4cm");
        column.Format.Alignment = ParagraphAlignment.Right;

        // Create the header of the table
        Row row = table.AddRow();
        row.HeadingFormat = true;
        row.Format.Alignment = ParagraphAlignment.Center;
        row.Format.Font.Bold = true;
        row.Shading.Color = Colors.Red;
        row.Cells[0].AddParagraph("Item");
        row.Cells[0].Format.Font.Bold = false;
        row.Cells[0].Format.Alignment = ParagraphAlignment.Left;
        row.Cells[0].VerticalAlignment = VerticalAlignment.Bottom;
        row.Cells[0].MergeDown = 1;
        row.Cells[1].AddParagraph("Title and Author");
        row.Cells[1].Format.Alignment = ParagraphAlignment.Left;
        row.Cells[1].MergeRight = 3;
        row.Cells[5].AddParagraph("Extended Price");
        row.Cells[5].Format.Alignment = ParagraphAlignment.Left;
        row.Cells[5].VerticalAlignment = VerticalAlignment.Bottom;
        row.Cells[5].MergeDown = 0;

        row = table.AddRow();
        row.HeadingFormat = true;
        row.Format.Alignment = ParagraphAlignment.Center;
        row.Format.Font.Bold = true;
        row.Shading.Color = Colors.Blue;
        row.Cells[1].AddParagraph("Quantity");
        row.Cells[1].Format.Alignment = ParagraphAlignment.Left;
        row.Cells[2].AddParagraph("Unit Price");
        row.Cells[2].Format.Alignment = ParagraphAlignment.Left;
        row.Cells[3].AddParagraph("Discount (%)");
        row.Cells[3].Format.Alignment = ParagraphAlignment.Left;
        row.Cells[4].AddParagraph("Taxable");
        row.Cells[4].Format.Alignment = ParagraphAlignment.Left;

        table.SetEdge(0, 0, 6, 2, Edge.Box, BorderStyle.Single, 0.75, Color.Empty);
    }

    static void FillContent()
    {
        

        Paragraph paragraph = addressFrame.AddParagraph();


        // Iterate the invoice items
        double totalExtendedPrice = 0;
       
            double quantity = 200;
            double price = 40;
            double discount = 5;
        for (int i = 0; i < 10; i++)
        {


            // Each item fills two rows
            Row row1 = table.AddRow();
            Row row2 = table.AddRow();
            row1.TopPadding = 1.5;
            row1.Cells[0].Shading.Color = Colors.Gray;
            row1.Cells[0].VerticalAlignment = VerticalAlignment.Center;
            row1.Cells[0].MergeDown = 1;
            row1.Cells[1].Format.Alignment = ParagraphAlignment.Left;
            row1.Cells[1].MergeRight = 3;
            row1.Cells[5].Shading.Color = Colors.Gray;
            row1.Cells[5].MergeDown = 1;

            row1.Cells[0].AddParagraph("Hello World 300");
            paragraph = row1.Cells[1].AddParagraph();
            paragraph.AddFormattedText("Hello World 234", TextFormat.Bold);
            paragraph.AddFormattedText(" by ", TextFormat.Italic);
            paragraph.AddText("Hello World 200");
            row2.Cells[1].AddParagraph("Hello World 125");
            row2.Cells[2].AddParagraph(price.ToString("0.00") + " €");
            row2.Cells[3].AddParagraph(discount.ToString("0.0"));
            row2.Cells[4].AddParagraph();
            row2.Cells[5].AddParagraph(price.ToString("0.00"));
            double extendedPrice = quantity * price;
            extendedPrice = extendedPrice * (100 - discount) / 100;
            row1.Cells[5].AddParagraph(extendedPrice.ToString("0.00") + " €");
            row1.Cells[5].VerticalAlignment = VerticalAlignment.Bottom;
            totalExtendedPrice += extendedPrice;

            table.SetEdge(0, table.Rows.Count - 2, 6, 2, Edge.Box, BorderStyle.Single, 0.75);

        }

    }