使用itextsharp向pdf添加段落的问题

时间:2011-02-21 07:12:08

标签: c# asp.net itextsharp paragraphs

我有以下代码,其pdf文件中的输出是:

  

表格M.T.R. 17

     

PAY-BILL OF GAZETTED OFFICER

                                DDO Code: 703

代码是:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;

using iTextSharp.text;
using iTextSharp.text.pdf;
public partial class new_salary : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ContentType = "application/pdf";

        // Create PDF document
        Document pdfDocument = new Document(PageSize.A4, 70, 45, 40, 25);

        PdfWriter wri = PdfWriter.GetInstance(pdfDocument, new FileStream("d://JudgeSalary.pdf", FileMode.Create));

        PdfWriter.GetInstance(pdfDocument, HttpContext.Current.Response.OutputStream);

        pdfDocument.Open();

        Chunk boo = new Chunk("Form M.T.R. 17");


        Paragraph main1 = new Paragraph("Form M.T.R. 17 \nPAY-BILL OF GAZETTED OFFICER");
        main1.Alignment = Element.ALIGN_CENTER;
        main1.Font.SetStyle(Font.BOLD);

        Paragraph main1a = new Paragraph("          DDO Code: 703");
        main1a.Alignment = Element.ALIGN_RIGHT;





        pdfDocument.Add(main1);
        pdfDocument.Add(main1a);

        pdfDocument.Close();
        HttpContext.Current.Response.End();
    }
}

我希望输出为:

               **Form M.T.R. 17**

               **PAY-BILL OF GAZETTED OFFICER**                           DDO Code: 703

如何在段落的第二行使用'DDO Code:703'获得上述输出,并且没有文本格式。如果我在'para1'中包含'DDO Code:703',则文本显示为粗体。 我希望此输出为中心对齐接受'DDO代码:703',我想要正确对齐。

我不希望它显示为粗体,也希望它在段落的第2行。我该怎么做?

2 个答案:

答案 0 :(得分:2)

使用iTextSharp,您可以使用ChunkPhraseParagraph添加文字。请参阅有关这些工作 here 的参考资料。从本质上讲,您需要将段落放在一起作为几个短语或块,以允许不同的字体样式。

要实现所需的定位,具有适当对齐的PdfPTable元素的PdfPCell可能效果最佳。如下所示:

PdfPTable table = new PdfPTable(2);
PdfPCell cell = new PdfPCell(new Phrase("Form M.T.R. 17", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12, iTextSharp.text.Font.BOLD)));
cell.Colspan = 2;
cell.Border = 0;
cell.HorizontalAlignment = Element.ALIGN_LEFT; 
table.AddCell(cell);
table.AddCell(new Phrase("PAY-BILL OF GAZETTED OFFICER"));

PdfPCell rCell = new PdfPCell(new Phrase("DDO Code: 703", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12)));
rCell.Border = 0;
rCell.HorizontalAlignment = Element.ALIGN_RIGHT; 
table.AddCell(rCell);
pdfDocument.Add(table);

答案 1 :(得分:0)

一个段落将在一个新行中,尝试使用这样的短语:

Phrase main1 = new Phrase("Form M.T.R. 17 \nPAY-BILL OF GAZETTED OFFICER");
main1.Font.SetStyle(Font.BOLD);

Phrase main1a = new Paragraph(" DDO Code: 703");

pdfDocument.Add(main1);
pdfDocument.Add(main1a);