我正在使用下面的代码来创建一个标题页。

public static byte[] CreatePageHeader(List<string> texts) {
        var stream = new MemoryStream();
        Document doc = null;

        try {
            doc = new Document();
            PdfWriter.GetInstance(doc, stream);
            doc.SetMargins(50, 50, 50, 50);
            doc.SetPageSize(new iTextSharp.text.Rectangle(iTextSharp.text.PageSize.LETTER.Width, iTextSharp.text.PageSize.LETTER.Height));
            Font font = new Font(Font.FontFamily.HELVETICA, 10f, Font.NORMAL);
            doc.Open();

            Paragraph para = null;
            foreach (string text in texts) {
                para = new Paragraph(text, font);
                doc.Add(para);
            }

        } catch (Exception ex) {
            throw ex;
        } finally {
            doc.Close();
        }

        return stream.ToArray();
    }

这工作正常,但它在页面顶部显示文本。
但我希望它在页面的中间。

请我如何修改此代码执行此操作?

最佳答案

我只需要一个单行单列表。这些类型的对象支持设置固定的宽度/高度,允许您“居中”事物。

var outputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf");
using (var fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
    using (var doc = new Document()) {
        using (var writer = PdfWriter.GetInstance(doc, fs)) {
            doc.Open();

            //Create a single column table
            var t = new PdfPTable(1);

            //Tell it to fill the page horizontally
            t.WidthPercentage = 100;

            //Create a single cell
            var c = new PdfPCell();

            //Tell the cell to vertically align in the middle
            c.VerticalAlignment = Element.ALIGN_MIDDLE;

            //Tell the cell to fill the page vertically
            c.MinimumHeight = doc.PageSize.Height - (doc.BottomMargin + doc.TopMargin);

            //Create a test paragraph
            var p = new Paragraph("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam iaculis sem diam, quis accumsan ipsum venenatis ac. Pellentesque nec gravida tortor. Suspendisse dapibus quis quam sed sollicitudin.");

            //Add it a couple of times
            c.AddElement(p);
            c.AddElement(p);

            //Add the cell to the paragraph
            t.AddCell(c);

            //Add the table to the document
            doc.Add(t);
            doc.Close();
        }
    }
}

关于c# - Itextsharp:如何在页面中间放置文本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17087154/

10-13 02:43