使用PDFsharp添加文本行

时间:2018-07-25 06:36:47

标签: c# pdfsharp

我正在使用PDFsharp创建PDF文件。我的问题是,当我将文本行放到PDF时,我只能得到一行。很自然,所有适合第一行的文本都是可见的,因为其他文本超出了范围。 enter image description here

请在下面查看我的代码:

private void createPdf2()
        {
            var title = DateTime.Now.ToString("MM-dd-yyyy-hh-m-ss") + "-" + txtPlazaNumber.Text + "-" + txtLaneNumber.Text;
            var now = DateTime.Now;
            var sb = new StringBuilder();
            sb.AppendLine("Date: " + DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss")).AppendLine(Environment.NewLine);
            sb.AppendLine("Plaza Number: " + txtPlazaNumber.Text).AppendLine(Environment.NewLine);
            sb.AppendLine("Lane Number: " + txtLaneNumber.Text).AppendLine(Environment.NewLine);
            sb.AppendLine("RFID IP Address: " + txtRfidIpAddress.Text).AppendLine(Environment.NewLine);
            sb.AppendLine("RFID Port: " + nRfidPort.Text).AppendLine(Environment.NewLine);
            sb.AppendLine("TFI IP Address: " + txtTfiIpAddress.Text).AppendLine(Environment.NewLine);
            sb.AppendLine("QR Port: " + nQrPort.Text).AppendLine(Environment.NewLine);

            sb.AppendLine("Passed Tests").AppendLine();
            foreach(var p in passedList)
            {
                sb.AppendLine("\t").Append(p.Trim()).AppendLine();
            }
            sb.AppendLine("Failed Tests").AppendLine();
            foreach(var f in failedList)
            {
                sb.AppendLine("\f").Append(f.Trim()).AppendLine();
            }

            PdfDocument pdf = new PdfDocument();
            pdf.Info.Title = title;
            PdfPage pdfPage = pdf.AddPage();
            XGraphics graph = XGraphics.FromPdfPage(pdfPage);
            XFont font = new XFont("Verdana", 12, XFontStyle.Regular);
            graph.DrawString(sb.ToString(), font, XBrushes.Black, new XRect(0, 0, pdfPage.Width.Point, pdfPage.Height.Point), XStringFormats.TopLeft);
            string pdfFilename = title + ".pdf";
            pdf.Save(pdfFilename);
}

1 个答案:

答案 0 :(得分:1)

这有点棘手。您需要一个XTextFormatter,一个用于布局器可用区域的XRect,然后在格式器而不是XGraphics对象上调用DrawString(…):

var formatter = new XTextFormatter(pageGraphics);
var layoutRectangle = new XRect(10, 10, page.Width, page.Height);
formatter.DrawString("Hello\r\nWorld", arial, XBrushes.Black, layoutRectangle);

http://development.wellisolutions.de/generating-pdf-with-pdfsharp/