如何使用iTextSharp的使用C#创建PDF插入HTML标记? [英] How to Insert HTML markup using iTextSharp for creating PDF using C#?

查看:204
本文介绍了如何使用iTextSharp的使用C#创建PDF插入HTML标记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的 iTextSharp的API 以创建 PDF 。我想创建在下面的图片中所示的一个 PDF 相似:

我已经加入表( PdfPTable )来显示左侧部分(比橙界定其他文本)

I am new to iTextSharp API to create PDF. I want to Create the a PDF similar shown in following image: I have added Table(PdfPTable) to Display the Left part (Text other than the Orange Bordered)

protected void CreatePDF()
{
    //Create PDF slip
    PdfPTable pdfTabdevices = new PdfPTable(2);
    DataTable dt = Session["MyList"] as DataTable;
    pdfTabdevices = GetDataFromSQLTable(dt);//Get the device lists
    Document doc = new Document(iTextSharp.text.PageSize.A4, 20, 20, 42,35);//iTextSharp.text.PageSize.Letter, 10, 10, 42,35
    int orderid = Session["OrderID"] != null ? Convert.ToInt32(Session["OrderID"]) : 0;

    try
    {
        string pdfFilePath = Server.MapPath(".") + "/pdfdocs/" + orderid + ".pdf";

        //Create Document class object and set its size to letter and give space left, right, Top, Bottom Margin
        PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(pdfFilePath, FileMode.Create));

        doc.Open();//Open Document to write

        Font font8 = FontFactory.GetFont("ARIAL", 7);
        string imageFilePath = Server.MapPath(".") + "/images/Logo.png";
        iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageFilePath);
        //Resize image depend upon your need
        jpg.ScaleToFit(100f, 50f);//jpg.ScaleToFit(280f, 260f);
        //Give space before image
        jpg.SpacingBefore = 30f;
        //Give some space after the image
        jpg.SpacingAfter = 1f;
        jpg.Alignment = Element.ALIGN_LEFT;
        doc.Add(jpg);

        Phrase titl = new Phrase("\n\nPacking Slip\n");
        titl.Font.SetStyle(Font.BOLD);
        doc.Add(titl);

        Phrase titlDesc = new Phrase("Place this slip inside the box with your device");
        // titlDesc.Font.SetStyle(Font.BOLD);
        doc.Add(titlDesc);
        doc.Add(pdfTabdevices);

        string expdate = Convert.ToString(DateTime.Now.Date);
        Phrase expir = new Phrase("You have until " + expdate + " to ship your device.");
        // titlDesc.Font.SetStyle(Font.BOLD);
        doc.Add(expir);

        Phrase note = new Phrase("\n\nIf you send your device after the expiration date we cannot honor your initial offer. We will not accept devices that have been reported lost or stolen.");
        doc.Add(note);
    }
    catch (DocumentException docEx)
    {
        //handle pdf document exception if any
    }
    catch (IOException ioEx)
    {
        // handle IO exception
    }
    catch (Exception ex)
    {
        // ahndle other exception if occurs
    }
    finally
    {
        //Close document and writer
        doc.Close();
    }
}

protected PdfPTable GetDataFromSQLTable(DataTable dt)
{
    PdfPTable table = new PdfPTable(2);
    //actual width of table in points
    table.TotalWidth = 500f;//216f;
    //fix the absolute width of the table
    table.LockedWidth = true;

    //relative col widths in proportions -  2/3 & 1/3 
    float[] widths = new float[] { 2f, 1f };
    table.SetWidths(widths);
    table.HorizontalAlignment = 0;
    //leave a gap before and after the table
    table.SpacingBefore = 20f;
    table.SpacingAfter = 20f;

    //PdfPCell cell2 = new PdfPCell(new Phrase("ITEM"));
    PdfPCell cell2 = new PdfPCell(new Phrase("ITEM", new Font(Font.HELVETICA, 10f, Font.BOLD, Color.BLACK)));
    cell2.Border = Rectangle.BOTTOM_BORDER;
    cell2.BorderColor=Color.WHITE;

    table.AddCell(cell2);

    //PdfPCell cell = new PdfPCell(new Phrase("OFFER"));
    PdfPCell cell = new PdfPCell(new Phrase("OFFER", new Font(Font.HELVETICA, 10f, Font.BOLD, Color.BLACK)));
    cell2.Border = Rectangle.BOTTOM_BORDER;
    cell.BorderColor = Color.WHITE;
    //cell.Colspan = 2;
    //cell.Border = 0;
    //cell.HorizontalAlignment = 1;//0=Left, 1=Centre, 2=Right
    table.AddCell(cell);


    DataTable dtmain = new DataTable();
    dtmain = dt;
    double boxTotal = 0.00;
    if (dtmain.Rows.Count > 0)
    {
        for (int i = 0; i < dtmain.Rows.Count; i++)
        {
            PdfPCell rcol1 =new PdfPCell(new Phrase(dtmain.Rows[i]["DeviceName"].ToString(), new Font(Font.HELVETICA, 10f, Font.NORMAL, Color.BLACK)));
            rcol1.BorderColor = Color.WHITE;
            table.AddCell(rcol1);

            //table.AddCell(dtmain.Rows[i]["DeviceName"].ToString());

            PdfPCell rcol2 = new PdfPCell(new Phrase("$" + dtmain.Rows[i]["Price"].ToString(), new Font(Font.HELVETICA, 10f, Font.NORMAL, Color.BLACK)));
            rcol2.BorderColor = Color.WHITE;
            table.AddCell(rcol2);

            //table.AddCell("$" +dtmain.Rows[i]["Price"].ToString());
            boxTotal+= Convert.ToDouble(dtmain.Rows[i]["Price"]);
        }
    }

    PdfPCell rcolSecLast1 = new PdfPCell(new Phrase("---------------------------------------------------------------------------------", new Font(Font.HELVETICA, 12f, Font.BOLD, Color.BLACK)));
    rcolSecLast1.BorderColor = Color.WHITE;
    table.AddCell(rcolSecLast1);


    PdfPCell rcolSecLast2 = new PdfPCell(new Phrase("--------------", new Font(Font.HELVETICA, 12f, Font.BOLD, Color.BLACK)));
    rcolSecLast2.BorderColor = Color.WHITE;
    table.AddCell(rcolSecLast2);

    PdfPCell rcolLast = new PdfPCell(new Phrase("Total Offer  :", new Font(Font.HELVETICA, 12f, Font.BOLD, Color.BLACK)));

    rcolLast.BorderColor = Color.WHITE;
    table.AddCell(rcolLast);

    //table.AddCell("Total Offer  :");

    PdfPCell rcolLast1 = new PdfPCell(new Phrase(String.Format("{0:C}", boxTotal).ToString(), new Font(Font.HELVETICA, 12f, Font.BOLD, Color.BLACK)));

    rcolLast1.BorderColor = Color.WHITE;
    table.AddCell(rcolLast1);

    //table.AddCell(String.Format("{0:C}",boxTotal).ToString());
    return table;      
}

不过,我很拉不上来使用'PdfPTable'与橙色边框箱及其内容并调整到右,如图2所示。。那么,是他们的任何其他方法来输入HTML标记到 PdfPTable

But, i am Not able to Draw the Box with Orange Border and its contents using the 'PdfPTable' and align to right as shown in fig.. So, is their any other method to input HTML Markup in to the PdfPTable?

请给建议做..!

请注意:当用户完成创建并保存到一个文件夹中的PDF文件,而不是下载或查看,能够用户

Note: when user completes the PDF file is created and saved to a folder and not downloaded or view-able to user.

HTML标记:

 <div style='width: 50%; border: 1px solid #000000; padding-bottom: 100px; padding-left: 100px;
        padding-right: 100px; text-align: justify; text-justify: inter-word;'>
        <br />
        <table>
            <tr>
                <td>
                    <div id="divLeft">
                        <p>
                            <img src='/images/Logo.png' width="200px" height="100px" /></p>
                        <h2>
                            Packing slip</h2>
                        <h3>
                            Place this slip inside the box with your device.</h3>
                        <div id="divDeviceList" style='width: 600px; text-align: left;' border="0" cellpadding="3"
                            cellspacing="1" rules="BOTH" frame="BOX">
                            <table style="width: 600px;">
                                <tr>
                                    <td>
                                       <strong> ITEM</strong>
                                    </td>
                                    <td>
                                       <strong>  OFFER</strong>
                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                        iPhone 5 32GB (AT&T)
                                    </td>
                                    <td>
                                        $205.00
                                    </td>
                                </tr>

                                <tr>
                                    <td align="right">
                                    <hr />
                                     <strong><h3>Total Offer: &nbsp;</h3></strong>
                                    </td>
                                    <td>
                                    <hr />
                                      <strong> <h3>  $215.00</h3></strong>
                                    </td>
                                </tr>

                            </table>


                        </div>

                            <h3>
                                You have until 01/29/2014 to ship your device.</h3>
                        <p style="padding:10px;">
                            <i>If you send your device after the expiration date we cannot honor your initial offer.
                                We will not accept devices that have been reported lost or stolen.</i></p>
                        <br />
                    </div>
                </td>
                <td>
                    <div id="divRight">
                     <div style="text-align:right;padding:15px;"> <img src="../images/barcode.png" alt="barcode" /></div>
                        <table cellpadding="3" style="border: 1px solid orange;padding:20px;">

                        </tr>
                            <tr align="center">
                                <td>
                                   <img src="../images/pdfiphone.png" alt="iphone" />
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <h3>
                                        "Find my iPhone" must be turned off</h3>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    This feature locks your device and will delay or reduce payment.
                                </td>
                            </tr>
                            <tr>
                                <td>
                                 <strong>How to deactivate:</strong></td>
                            </tr>
                            <tr>
                                <td>
                                    1. Tap the "settings" icon on your homescreen.</td>
                            </tr>
                            <tr>
                                <td>
                                    2. Tap iCloud from the settings menu. </td>
                            </tr>
                            <tr>
                                <td>
                                    3. If "Find My iPhone" is on, tap the slider to turn it off.</td>
                            </tr>
                        </table>
                    </div>

我可以使用上面的HTML标记和替换字符串,并创建PDF并保存了观看或下载用户?到文件夹

推荐答案

在这里,你可以找到一个方法来做到

Here you can find a way to do

iTextSharp的HTML到PDF?

唯一的问题你会得到被定位图像,因为他们总是块,所以你需要从code设置它的后面。

Only issue you will get is locating images, as they are always block, so you need to set it from code behind.

这篇关于如何使用iTextSharp的使用C#创建PDF插入HTML标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆