c# pdf操作
2019-01-08 01:11:04 weixin_34249678 阅读数 188

 

 

 

 

 

Spire.PDF组件概述

Spire.PDF是一个专业的PDF组件,用于在.NET应用程序中创建,编辑,处理和阅读PDF文档。支持丰富的PDF文档处理操作,如PDF文档合并/拆分、转换(如HTML转PDF,PDF转图片等)、打印(包括静默打印)、压缩、添加/修改/删除书签、添加注释、安全设置(包括数字签名)、创建与填充域、图片插入与提取、文本提取与高亮等。它不依赖Adobe Acrobat,因此运行环境无需安装Adobe Reader或其他类似组件。 该组件分为商业版和免费版(不是试用版)两种,一般个人使用或者操作的PDF文档不超过10页时,可以使用免费版。

 

添加、修改和删除PDF书签的实现

一、添加书签

1.1 添加书签

在Spire.PDF中,每个PDF文档都有一个书签列表(PdfBookmarkCollection)。我们可以通过PdfDocument对象的Bookmarks属性来获取该列表,然后通过Add () 方法将书签添加到列表中。

//新建PDF文档

PdfDocument pdf = new PdfDocument();

//添加页面

PdfPageBase page = pdf.Pages.Add();

//添加书签
PdfBookmark bookmark = pdf.Bookmarks.Add("第一页");

//设置书签所指向的页面和位置,(0,0)表示页面的开始位置

bookmark.Destination = new PdfDestination(page);
bookmark.Destination.Location = new PointF(0, 0);

//设置书签的文本格式和颜色

bookmark.DisplayStyle = PdfTextStyle.Bold;
bookmark.Color = Color.Black;

//保存文档

pdf.SaveToFile("Bookmark2.pdf");

1.2 添加子书签

添加子书签和添加普通书签的方式基本一样,不同的是普通书签是直接添加到文档的书签列表里,而子书签则是添加到父书签的列表里。

//新建PDF文档

PdfDocument pdf = new PdfDocument();

//添加页面

PdfPageBase page = pdf.Pages.Add(); 

//添加书签

PdfBookmark bookmark = pdf.Bookmarks.Add("第一章 热传导");

//设置书签指向的页面和位置

bookmark.Destination = new PdfDestination(page);
bookmark.Destination.Location = new PointF(0, 0);
 
//设置书签的文本格式和颜色

bookmark.DisplayStyle = PdfTextStyle.Bold;
bookmark.Color = Color.SeaGreen;

//添加子书签

PdfBookmark childBookmark = bookmark.Insert(0, "1.1 热传导基本知识");

//设置子书签指向的页面和位置

childBookmark.Destination = new PdfDestination(page);
childBookmark.Destination.Location = new PointF(400, 300);

//设置子书签的文本格式和颜色

childBookmark.DisplayStyle = PdfTextStyle.Regular;
childBookmark.Color = Color.Black;

//保存文档

pdf.SaveToFile("ChildBookmark.pdf");

 

 

1.3 添加书签到现有文档

除了在新建的PDF文档里添加书签,我们还可以给现有的PDF文档添加书签。加载PDF文档的方法除LoadFromFile以外,还有LoadFromStream (从流加载),LoadFromHTML(从HTML加载)等,可根据自己的需求选择相应的加载方式。

//加载文档

PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("示例.pdf"); 

for (int i = 0; i < pdf.Pages.Count; i++)
{
    //添加书签

    PdfBookmark bookmark = pdf.Bookmarks.Add(string.Format("第{0}章", i+1));

    //设置书签指向的页面和位置

    bookmark.Destination = new PdfDestination(pdf.Pages[i]);
    bookmark.Destination.Location = new PointF(0, 0);

    //设置书签的文本格式和颜色

    bookmark.DisplayStyle = PdfTextStyle.Bold;
    bookmark.Color = Color.Black;
}

//保存文档

pdf.SaveToFile("Bookmark2.pdf");

 

 

2. 修改书签

Spire.PDF支持多种书签修改方式,例如修改现有书签的内容,插入新书签到现有书签列表,插入子书签到现有书签等。这里我选取修改书签内容和插入新书签到现有书签列表进行介绍。

2.1 修改现有书签内容

//加载文档

PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("Bookmark2.pdf");

//获取书签列表

PdfBookmarkCollection bookmarks = pdf.Bookmarks;

//获取第一个书签

PdfBookmark bookmark = bookmarks[0];

//修改书签指向的页面

bookmark.Destination = new PdfDestination(document.Pages[1]); 

//修改书签的文本格式和颜色

bookmark.DisplayStyle = PdfTextStyle.Bold;
bookmark.Color = Color.Green;

//修改书签的title

bookmark.Title = "修改";

//保存文档

pdf.SaveToFile("ModifyBookmark.pdf");

 

2.2 插入新书签到现有书签列表

//加载文档
 
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("Bookmark2.pdf");
 
//插入新书签到指定位置(此处插入的是第三个书签的位置)
 
PdfBookmark bookmark = pdf.Bookmarks.Insert(2, "新增第三章");
 
//设置书签所指向的页面和位置
 
bookmark.Destination = new PdfDestination(document.Pages[1]);
bookmark.Destination.Location = new PointF(0, 300);
 
//保存文档
 
pdf.SaveToFile("InsertBookmark.pdf");

 

 

3. 删除书签

删除书签时,可以使用书签的序号,也可以使用书签的名称。这里我使用的是序号的方式。

//加载文档

PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("Bookmark2.pdf");

//获取书签列表

PdfBookmarkCollection bookmarks = document.Bookmarks;

//删除第一个书签

bookmarks.RemoveAt(0);

//保存文档

pdf.SaveToFile("DeleteBookmark.pdf");

 

 

转自:http://www.cnblogs.com/Yesi/p/7251214.html

 

2019-07-30 04:53:56 weixin_30953169 阅读数 8

 

 

 

 

 

Spire.PDF组件概述

Spire.PDF是一个专业的PDF组件,用于在.NET应用程序中创建,编辑,处理和阅读PDF文档。支持丰富的PDF文档处理操作,如PDF文档合并/拆分、转换(如HTML转PDF,PDF转图片等)、打印(包括静默打印)、压缩、添加/修改/删除书签、添加注释、安全设置(包括数字签名)、创建与填充域、图片插入与提取、文本提取与高亮等。它不依赖Adobe Acrobat,因此运行环境无需安装Adobe Reader或其他类似组件。 该组件分为商业版和免费版(不是试用版)两种,一般个人使用或者操作的PDF文档不超过10页时,可以使用免费版。

 

添加、修改和删除PDF书签的实现

一、添加书签

1.1 添加书签

在Spire.PDF中,每个PDF文档都有一个书签列表(PdfBookmarkCollection)。我们可以通过PdfDocument对象的Bookmarks属性来获取该列表,然后通过Add () 方法将书签添加到列表中。

//新建PDF文档

PdfDocument pdf = new PdfDocument();

//添加页面

PdfPageBase page = pdf.Pages.Add();

//添加书签
PdfBookmark bookmark = pdf.Bookmarks.Add("第一页");

//设置书签所指向的页面和位置,(0,0)表示页面的开始位置

bookmark.Destination = new PdfDestination(page);
bookmark.Destination.Location = new PointF(0, 0);

//设置书签的文本格式和颜色

bookmark.DisplayStyle = PdfTextStyle.Bold;
bookmark.Color = Color.Black;

//保存文档

pdf.SaveToFile("Bookmark2.pdf");

1.2 添加子书签

添加子书签和添加普通书签的方式基本一样,不同的是普通书签是直接添加到文档的书签列表里,而子书签则是添加到父书签的列表里。

//新建PDF文档

PdfDocument pdf = new PdfDocument();

//添加页面

PdfPageBase page = pdf.Pages.Add(); 

//添加书签

PdfBookmark bookmark = pdf.Bookmarks.Add("第一章 热传导");

//设置书签指向的页面和位置

bookmark.Destination = new PdfDestination(page);
bookmark.Destination.Location = new PointF(0, 0);
 
//设置书签的文本格式和颜色

bookmark.DisplayStyle = PdfTextStyle.Bold;
bookmark.Color = Color.SeaGreen;

//添加子书签

PdfBookmark childBookmark = bookmark.Insert(0, "1.1 热传导基本知识");

//设置子书签指向的页面和位置

childBookmark.Destination = new PdfDestination(page);
childBookmark.Destination.Location = new PointF(400, 300);

//设置子书签的文本格式和颜色

childBookmark.DisplayStyle = PdfTextStyle.Regular;
childBookmark.Color = Color.Black;

//保存文档

pdf.SaveToFile("ChildBookmark.pdf");

 

 

1.3 添加书签到现有文档

除了在新建的PDF文档里添加书签,我们还可以给现有的PDF文档添加书签。加载PDF文档的方法除LoadFromFile以外,还有LoadFromStream (从流加载),LoadFromHTML(从HTML加载)等,可根据自己的需求选择相应的加载方式。

//加载文档

PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("示例.pdf"); 

for (int i = 0; i < pdf.Pages.Count; i++)
{
    //添加书签

    PdfBookmark bookmark = pdf.Bookmarks.Add(string.Format("第{0}章", i+1));

    //设置书签指向的页面和位置

    bookmark.Destination = new PdfDestination(pdf.Pages[i]);
    bookmark.Destination.Location = new PointF(0, 0);

    //设置书签的文本格式和颜色

    bookmark.DisplayStyle = PdfTextStyle.Bold;
    bookmark.Color = Color.Black;
}

//保存文档

pdf.SaveToFile("Bookmark2.pdf");

 

 

2. 修改书签

Spire.PDF支持多种书签修改方式,例如修改现有书签的内容,插入新书签到现有书签列表,插入子书签到现有书签等。这里我选取修改书签内容和插入新书签到现有书签列表进行介绍。

2.1 修改现有书签内容

//加载文档

PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("Bookmark2.pdf");

//获取书签列表

PdfBookmarkCollection bookmarks = pdf.Bookmarks;

//获取第一个书签

PdfBookmark bookmark = bookmarks[0];

//修改书签指向的页面

bookmark.Destination = new PdfDestination(document.Pages[1]); 

//修改书签的文本格式和颜色

bookmark.DisplayStyle = PdfTextStyle.Bold;
bookmark.Color = Color.Green;

//修改书签的title

bookmark.Title = "修改";

//保存文档

pdf.SaveToFile("ModifyBookmark.pdf");

 

2.2 插入新书签到现有书签列表

//加载文档
 
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("Bookmark2.pdf");
 
//插入新书签到指定位置(此处插入的是第三个书签的位置)
 
PdfBookmark bookmark = pdf.Bookmarks.Insert(2, "新增第三章");
 
//设置书签所指向的页面和位置
 
bookmark.Destination = new PdfDestination(document.Pages[1]);
bookmark.Destination.Location = new PointF(0, 300);
 
//保存文档
 
pdf.SaveToFile("InsertBookmark.pdf");

 

 

3. 删除书签

删除书签时,可以使用书签的序号,也可以使用书签的名称。这里我使用的是序号的方式。

//加载文档

PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("Bookmark2.pdf");

//获取书签列表

PdfBookmarkCollection bookmarks = document.Bookmarks;

//删除第一个书签

bookmarks.RemoveAt(0);

//保存文档

pdf.SaveToFile("DeleteBookmark.pdf");

 

 

转自:http://www.cnblogs.com/Yesi/p/7251214.html

 

转载于:https://www.cnblogs.com/allen0118/p/7253971.html

2012-04-11 18:10:00 weixin_30947043 阅读数 2

一:PDF

1.Adobe Acrobat 8 Professional 可以修改和制作模板

2.向模板插入数据(代码)例子,需要用到itextsharp.dll引用文件

 

using System;
using System.Collections.Generic;
using System.Web;
using iTextSharp.text;
using System.IO;
using iTextSharp.text.pdf;
using System.Data;
using Suryani.Commerce.Core.Common;
using System.Text;
using Suryani.Commerce.Core.Order_Mgmt;
using Diapers.Intranet.Manager;

/// <summary>
/// Summary description for InvoiceEmailGenerator
/// </summary>
public class InvoiceEmailGenerator
{
    private const string DIAPERS_CUSTOMER_TEMPLATE_NAME = "customerEmail_PDF_Invoice_Diapers";
    private const string SOAP_CUSTOMER_TEMPLATE_NAME = "customerEmail_PDF_Invoice_Soap";
    private const string BEAUTYBAR_CUSTOMER_TEMPLATE_NAME = "customerEmail_PDF_Invoice_BeautyBar";
    private const string WAG_CUSTOMER_TEMPLATE_NAME = "customerEmail_PDF_Invoice_Wag";
    private const string YOYO_CUSTOMER_TEMPLATE_NAME = "customerEmail_PDF_Invoice_Yoyo";
    private const string CASA_CUSTOMER_TEMPLATE_NAME = "customerEmail_PDF_Invoice_Casa";
    private const string USER_TEMPLATE_NAME = "1800diapers_PdfInvoiceForUser";
    private const string USER_TEMPLATE_NAME_POREINVOICE = "customerEmail_PDF_Invoice_PoOrder";
    private int CatalogID = 1;  //default is diapers
    private int SentTime = 1;  //default is diapers
    public InvoiceEmailGenerator()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    /// <summary>
    /// this function is for send invoice for customer
    /// </summary>
    /// <param name="orderId"></param>
    /// <param name="email"></param>
    /// <param name="templatePath"></param>
    /// <param name="isSendToCustomer"></param>
    /// <param name="shipmentId"></param>
    /// <returns></returns>
    public string GenerateAndSendInvoiceEmail(int orderId, string email, string templatePath, bool isSendToCustomer, int shipmentId,string dueDate)
    {
        if (orderId != -1 && !string.IsNullOrEmpty(email))
        {
            CatalogID = GetOrderCatalog(orderId);
            SentTime = GetPoOrderInvoiceTimes(orderId);
            //get catalog info
            DataTable catalog = new CatalogManager().GetAllCatalog();
            DataRow[] row = catalog.Select("CatalogId='" + CatalogID + "'");
            string contractPhoneInfo =row[0]["AddressToName"].ToString()+": " + row[0]["ShipperPhone"].ToString();
            string catalogName = row[0]["catalogName"].ToString();

            string fileName = "InvoiceTemplate" + System.DateTime.Now.Millisecond.ToString() + new Random().Next().ToString() + ".pdf";
            //sendResultLable.InnerText = "";
            Suryani.Commerce.Core.Order_Mgmt.Order order = new Suryani.Commerce.Core.Order_Mgmt.Order_Manager().GetOrder(orderId);
            string trackingNumber = string.Empty;
            bool isNotPaid = CheckPOOrderPaid(order);
            if (order != null && order.OrderItems != null && order.OrderItems.Rows.Count > 0)
            {
                Document document = null;
                FileStream invoicePdfStream = null;
                PdfCopy copy = null;
                PdfReader template1 = null;
                PdfReader template2_1 = null;
                PdfReader template2_2 = null;
                PdfStamper stamper = null;
                AcroFields fields = null;
                document = new Document();
                invoicePdfStream = new FileStream(string.Format("{0}\\{1}", templatePath, fileName), FileMode.Create);
                copy = new PdfCopy(document, invoicePdfStream);
                copy.SetFullCompression();
                copy.CloseStream = true;
                document.Open();
                //judge orderitems first,if the num of orderItems less than 16,we use template1
                //or we use template 2_1(29 rows) and template 2_2(15 rows), and how many template 2_1 will used result with this num.
                if (order.OrderItems.Rows.Count <= 16)
                {
                    template1 = GetTemplateByCatalogId(templatePath, 1);// new PdfReader(string.Format("{0}\\InvoiceTemplate1.pdf", templatePath));
                    MemoryStream invoiceStream = new MemoryStream();
                    stamper = new PdfStamper(template1, invoiceStream);
                    stamper.SetFullCompression();
                    fields = stamper.AcroFields;
                    if (order.OrderShippings != null && order.OrderShippings.Length > 0)
                    {
                        FillBillToAndShipTo(order, fields, contractPhoneInfo, dueDate, SentTime);
                        //Order List
                        int rowIndex = 0;
                        foreach (DataRow orderItem in order.OrderItems.Rows)
                        {
                            FillOneOrderItem(fields, rowIndex, orderItem);
                            rowIndex++;
                        }
                        FillTotal(order, fields,catalogName,dueDate);
                    }
                    stamper.FormFlattening = true;
                    stamper.Close();
                    template1 = new PdfReader(invoiceStream.ToArray());
                    template1.RemoveUnusedObjects();
                    copy.AddPage(copy.GetImportedPage(template1, 1));
                }
                else
                {
                    template2_1 = GetTemplateByCatalogId(templatePath, 2);// new PdfReader(string.Format("{0}\\InvoiceTemplate2_1.pdf", templatePath));
                    template2_2 = GetTemplateByCatalogId(templatePath, 3);// new PdfReader(string.Format("{0}\\InvoiceTemplate2_2.pdf", templatePath));
                    int template2_1Num = order.OrderItems.Rows.Count / 29;
                    bool isNeedReserve = false;
                    if (order.OrderItems.Rows.Count % 29 > 15)
                    {
                        template2_1Num += 1;
                        isNeedReserve = true;
                    }
                    if (order.OrderItems.Rows.Count % 29 == 0)
                    {
                        isNeedReserve = true;
                    }
                    int totalItemsOfTemp2_1 = order.OrderItems.Rows.Count;
                    if (isNeedReserve)
                    {
                        totalItemsOfTemp2_1 -= 2;
                    }
                    for (int i = 0; i < template2_1Num; i++)  //how many template2_1 will used
                    {
                        template2_1 = GetTemplateByCatalogId(templatePath, 2);
                        MemoryStream template2_1InvoiceStream = new MemoryStream();
                        stamper = new PdfStamper(template2_1, template2_1InvoiceStream);
                        stamper.SetFullCompression();
                        //begin to fill fields
                        fields = stamper.AcroFields;
                        if (order.OrderShippings != null && order.OrderShippings.Length > 0)
                        {
                            FillBillToAndShipTo(order, fields, contractPhoneInfo, dueDate, SentTime);
                            //Order List
                            int rowIndex = 0;
                            int pageNst = i * 29;
                            for (int j = i * 29; j < (pageNst + 29) && j < totalItemsOfTemp2_1; j++)
                            {
                                DataRow orderItem = order.OrderItems.Rows[j];
                                FillOneOrderItem(fields, rowIndex, orderItem);
                                rowIndex++;
                            }
                            fields.SetField("CurrentPage", (i + 1).ToString());
                            fields.SetField("TotalPage", (template2_1Num + 1).ToString());
                        }
                        stamper.FormFlattening = true;
                        stamper.Close();
                        template2_1 = new PdfReader(template2_1InvoiceStream.ToArray());
                        template2_1.RemoveUnusedObjects();
                        copy.AddPage(copy.GetImportedPage(template2_1, 1));
                    }
                    //one template2_2 will used
                    MemoryStream template2_2InvoiceStream = new MemoryStream();
                    stamper = new PdfStamper(template2_2, template2_2InvoiceStream);
                    stamper.SetFullCompression();
                    fields = stamper.AcroFields;
                    if (order.OrderShippings != null && order.OrderShippings.Length > 0)
                    {
                        FillBillToAndShipTo(order, fields, contractPhoneInfo, dueDate, SentTime);
                        //Order List
                        if (order.OrderItems.Rows.Count % 29 <= 15 && order.OrderItems.Rows.Count % 29 > 0)
                        {
                            int rowIndex = order.OrderItems.Rows.Count % 29 - 1;
                            int lastRowIndex = order.OrderItems.Rows.Count - 1;
                            if (rowIndex >= 0)
                            {
                                for (int k = rowIndex; k >= 0; k--)
                                {
                                    DataRow orderItem = order.OrderItems.Rows[lastRowIndex];
                                    FillOneOrderItem(fields, rowIndex, orderItem);
                                    rowIndex--;
                                    lastRowIndex--;
                                }
                            }
                        }
                        else  //reserve 2 records for InvoiceTemplate2_2
                        {
                            int rowIndex = 0;
                            for (int i = order.OrderItems.Rows.Count - 2; i < order.OrderItems.Rows.Count; i++)
                            {
                                DataRow orderItem = order.OrderItems.Rows[i];
                                FillOneOrderItem(fields, rowIndex, orderItem);
                                rowIndex++;
                            }
                        }
                        fields.SetField("CurrentPage", (template2_1Num + 1).ToString());
                        fields.SetField("TotalPage", (template2_1Num + 1).ToString());
                        FillTotal(order, fields,catalogName,dueDate);
                    }
                    stamper.FormFlattening = true;
                    stamper.Close();
                    template2_2 = new PdfReader(template2_2InvoiceStream.ToArray());
                    template2_2.RemoveUnusedObjects();
                    copy.AddPage(copy.GetImportedPage(template2_2, 1));
                }

                document.Close();
                if (invoicePdfStream != null)
                {
                    invoicePdfStream.Close();
                }
                if (template1 != null)
                {
                    template1.Close();
                }
                if (template2_1 != null)
                {
                    template2_1.Close();
                }
                if (template2_2 != null)
                {
                    template2_2.Close();
                }

                bool isSuccess = SendEmail(fileName, email, templatePath, isSendToCustomer, orderId, shipmentId, CatalogID, SentTime);
                if (isSuccess)
                {
                    new Order_Manager().UpdatePoInvoiceTimes(orderId, SiCommerce.Intranet.Security.Secure.GetUserName());
                    return "Invoice email has been sent.";
                }
                else
                {
                    return "Customer invoice template lost.";
                }
            }
            else
            {
                throw new Exception("No order item to print.");
            }
        }
        return "";
    }

    private bool CheckPOOrderPaid(Suryani.Commerce.Core.Order_Mgmt.Order order)
    {
        if (order.GL.ToUpper() == "PO" || (order.OrderShippings[0].PaymentInfo != null && order.OrderShippings[0].PaymentInfo.IsPO.Trim().ToUpper() == "Y"))
        {
            if (order.OrderShippings[0].PaymentInfo.Paid == "N")
            {
                return true;
            }
        }
        return false;
    }

    private static void FillBillToAndShipTo(Suryani.Commerce.Core.Order_Mgmt.Order order, AcroFields fields, string contractPhoneInfo,string dueDate,int times)
    {
        fields.SetField("ContractNumber", contractPhoneInfo);
        fields.SetField("InvoiceDate", string.Format("{0:d}", Convert.ToDateTime(order.OrderDate)));
        fields.SetField("InvoiceNumber", order.OrderId.ToString());
        fields.SetField("PONumber", order.OrderShippings[0].ShippingInfo.PO);
        if (times==2)
        {
            fields.SetField("SecondCopy","2nd COPY");
            //fields.SetField("SecondCopy", times.ToString()+"nd COPY");
        }
        else if (times == 3)
        {
            fields.SetField("SecondCopy", "3rd COPY");
            //fields.SetField("SecondCopy", times.ToString()+"nd COPY");
        }
        else if (times >3)
        {
            fields.SetField("SecondCopy", times.ToString() + "th COPY");
        }
        else
        {
            fields.SetField("SecondCopy", " ");
        }
        if (string.IsNullOrEmpty(dueDate))
        {
            dueDate = new Suryani.Commerce.Core.Order_Mgmt.Order_Manager().GetDueDateByOrderId(order.OrderId);
            if (string.IsNullOrEmpty(dueDate))
                dueDate = "Upon Receipt";
        }
        fields.SetField("DueDate", dueDate);
        //Bill To
        int index = 0;
        if (!string.IsNullOrEmpty(order.OrderShippings[0].PaymentInfo.BillToName))
        {
            fields.SetField("BillTo" + index, order.OrderShippings[0].PaymentInfo.BillToName);
            index++;
        }
        if (!string.IsNullOrEmpty(order.OrderShippings[0].PaymentInfo.BillToAddress1))
        {
            fields.SetField("BillTo" + index, order.OrderShippings[0].PaymentInfo.BillToAddress1);
            index++;
        }
        if (!string.IsNullOrEmpty(order.OrderShippings[0].PaymentInfo.BillToAddress2))
        {
            fields.SetField("BillTo" + index, order.OrderShippings[0].PaymentInfo.BillToAddress2);
            index++;
        }
        if (!string.IsNullOrEmpty(order.OrderShippings[0].PaymentInfo.BillToAddress3))
        {
            fields.SetField("BillTo" + index, order.OrderShippings[0].PaymentInfo.BillToAddress3);
            index++;
        }
        StringBuilder cityStateZipStringBuilder = new StringBuilder();
        if (!string.IsNullOrEmpty(order.OrderShippings[0].PaymentInfo.BillToCity))
        {
            cityStateZipStringBuilder.Append(order.OrderShippings[0].PaymentInfo.BillToCity);
        }
        if (!string.IsNullOrEmpty(order.OrderShippings[0].PaymentInfo.BillToState))
        {
            if (cityStateZipStringBuilder.Length > 0)
            {
                cityStateZipStringBuilder.Append(", ");
            }
            cityStateZipStringBuilder.Append(order.OrderShippings[0].PaymentInfo.BillToState);
        }
        if (!string.IsNullOrEmpty(order.OrderShippings[0].PaymentInfo.BillToZIP))
        {
            if (cityStateZipStringBuilder.Length > 0)
            {
                cityStateZipStringBuilder.Append(" ");
            }
            cityStateZipStringBuilder.Append(order.OrderShippings[0].PaymentInfo.BillToZIP);
        }
        if (cityStateZipStringBuilder.Length > 0)
        {
            fields.SetField("BillTo" + index, cityStateZipStringBuilder.ToString());
            index++;
        }
        if (!string.IsNullOrEmpty(order.OrderShippings[0].PaymentInfo.BillToCountryCode))
        {
            fields.SetField("BillTo" + index, order.OrderShippings[0].PaymentInfo.BillToCountryCode);
            index++;
        }
        if (!string.IsNullOrEmpty(order.OrderShippings[0].PaymentInfo.Phone))
        {
            fields.SetField("BillTo" + index, "Phone: " + order.OrderShippings[0].PaymentInfo.Phone);
        }

        //Ship TO
        index = 0;
        if (!string.IsNullOrEmpty(order.OrderShippings[0].ShippingInfo.RecipientName))
        {
            fields.SetField("ShipTo" + index, order.OrderShippings[0].ShippingInfo.RecipientName);
            index++;
        }
        if (!string.IsNullOrEmpty(order.OrderShippings[0].ShippingInfo.ShippingAddr1))
        {
            fields.SetField("ShipTo" + index, order.OrderShippings[0].ShippingInfo.ShippingAddr1);
            index++;
        }
        if (!string.IsNullOrEmpty(order.OrderShippings[0].ShippingInfo.ShippingAddr2))
        {
            fields.SetField("ShipTo" + index, order.OrderShippings[0].ShippingInfo.ShippingAddr2);
            index++;
        }
        if (!string.IsNullOrEmpty(order.OrderShippings[0].ShippingInfo.ShippingAddr3))
        {
            fields.SetField("ShipTo" + index, order.OrderShippings[0].ShippingInfo.ShippingAddr3);
            index++;
        }
        cityStateZipStringBuilder = new StringBuilder();
        if (!string.IsNullOrEmpty(order.OrderShippings[0].ShippingInfo.ShippingCity))
        {
            cityStateZipStringBuilder.Append(order.OrderShippings[0].ShippingInfo.ShippingCity);
        }
        if (!string.IsNullOrEmpty(order.OrderShippings[0].ShippingInfo.ShippingState))
        {
            if (cityStateZipStringBuilder.Length > 0)
            {
                cityStateZipStringBuilder.Append(", ");
            }
            cityStateZipStringBuilder.Append(order.OrderShippings[0].ShippingInfo.ShippingState);
        }
        if (!string.IsNullOrEmpty(order.OrderShippings[0].ShippingInfo.ShippingZip))
        {
            if (cityStateZipStringBuilder.Length > 0)
            {
                cityStateZipStringBuilder.Append(" ");
            }
            cityStateZipStringBuilder.Append(order.OrderShippings[0].ShippingInfo.ShippingZip);
        }
        if (cityStateZipStringBuilder.Length > 0)
        {
            fields.SetField("ShipTo" + index, cityStateZipStringBuilder.ToString());
            index++;
        }
        if (!string.IsNullOrEmpty(order.OrderShippings[0].ShippingInfo.ShippingCountry))
        {
            fields.SetField("ShipTo" + index, order.OrderShippings[0].ShippingInfo.ShippingCountry);
            index++;
        }
        if (!string.IsNullOrEmpty(order.OrderShippings[0].ShippingInfo.DayPhone))
        {
            fields.SetField("ShipTo" + index, "Phone: " + order.OrderShippings[0].ShippingInfo.DayPhone);
        }
    }

    private static void FillOneOrderItem(AcroFields fields, int rowIndex, DataRow orderItem)
    {
        fields.SetField("ItemNo" + rowIndex, orderItem["sku"].ToString());
        fields.SetField("Description" + rowIndex, orderItem["productname"].ToString());
        fields.SetField("QtyOrdered" + rowIndex, orderItem["quantity"].ToString());
        fields.SetField("QtyShipped" + rowIndex, orderItem["shipQty"].ToString());
        fields.SetField("UnitPrice" + rowIndex, string.Format("{0:c}", Convert.ToDouble(orderItem["discountprice"])));
        fields.SetField("Discount" + rowIndex, string.Format("{0:c}", Convert.ToDouble(orderItem["discount"])));
        fields.SetField("Subtotal" + rowIndex, string.Format("{0:c}", Convert.ToDouble(orderItem["Subtotal"]) - Convert.ToDouble(orderItem["discount"])));
    }

    private static void FillTotal(Suryani.Commerce.Core.Order_Mgmt.Order order, AcroFields fields, string catalogName,string dueDate)
    {
        fields.SetField("Subtotal", string.Format("{0:c}", order.TotalAmount - order.Discount));
        fields.SetField("Shipping", string.Format("{0:c}", order.OrderShippings[0].ShippingInfo.ShippingFee));
        fields.SetField("Credit", "-" + string.Format("{0:c}", order.Credit + order.Commission_Credit + order.GCCredit));
        fields.SetField("Coupon", "-" + string.Format("{0:c}", order.CouponValue));
        fields.SetField("GiftCertificate", "-" + string.Format("{0:c}", order.GCCredit));
        fields.SetField("Tax", string.Format("{0:c}", order.Tax));
        fields.SetField("Total", string.Format("{0:c}", order.TotalAmount + order.Tax - order.Credit + order.OrderShippings[0].ShippingInfo.ShippingFee - order.CouponValue - order.Discount - order.GCCredit - order.Commission_Credit));
        if (string.IsNullOrEmpty(dueDate))
        {
            dueDate = new Suryani.Commerce.Core.Order_Mgmt.Order_Manager().GetDueDateByOrderId(order.OrderId);
            if (string.IsNullOrEmpty(dueDate))
                dueDate = "Upon Receipt";
        }
        if (!dueDate.Equals("Paid"))
        {
            fields.SetField("msg1", "Please make check payable to \"Quidsi Retail LLC.\" and send to:");
            fields.SetField("msg2", catalogName);
            fields.SetField("msg3", "ATTN Accounts Receivable");
            fields.SetField("msg4", "10 Exchange PL, 25th FL");
            fields.SetField("msg5", "Jersey City, NJ 07302");
        }
    }

    private bool SendEmail(string fileName, string email, string templatePath, bool isSendToCustomer, int orderId, int shipmentId,int catalogID,int times)
    {
        string subject = string.Empty;
        string body = string.Empty;
        string from = string.Empty;
        if (isSendToCustomer)
        {
            if (times>1)
            {
                DataTable customerTemplate = new Suryani.Commerce.Core.Manager.TemplateManager().GetCustomerEmailTemplateForHoldOrderReport(USER_TEMPLATE_NAME_POREINVOICE);
                if (customerTemplate != null && customerTemplate.Rows.Count > 0)
                {
                    string title = new CatalogManager().GetCatalogCode(catalogID);
                    if (!string.IsNullOrEmpty(title))
                    {
                        title = title + ".com";
                    }
                    //if(catalogID==2)
                    //{
                    //    title="Soap.com";
                    //}
                    //else if(catalogID==3)
                    //{
                    //    title="BeautyBar.com";
                    //}
                    //else if(catalogID==4)
                    //{
                    //    title="Wag.com";
                    //}
                    //else if(catalogID==5)
                    //{
                    //    title="Yoyo.com";
                    //}
                    //else
                    //{
                    //    title="Diapers.com";
                    //}
                    from =customerTemplate.Rows[0]["FromEmailAddress"].ToString();
                    subject = customerTemplate.Rows[0]["Subject"].ToString();
                    body = string.Format(customerTemplate.Rows[0]["Body"].ToString(), title);     
                }
            }
            else
            {
            DataTable customerTemplate = GetInvoiceTemplate(catalogID);
            string fromAddres = "";
            if (SiCommerce.Intranet.Security.Secure.IsPOTeam())
            {
                fromAddres = "purchase.orders@diapers.com";
            }
            if (customerTemplate != null && customerTemplate.Rows.Count > 0)
            {   
                from = string.IsNullOrEmpty(fromAddres) ? customerTemplate.Rows[0]["FromEmailAddress"].ToString() : fromAddres; ;
                fromAddres=string.IsNullOrEmpty(fromAddres)?customerTemplate.Rows[0]["ReplyTo"].ToString():fromAddres;
                subject = customerTemplate.Rows[0]["Subject"].ToString();
                body = string.Format(customerTemplate.Rows[0]["Body"].ToString(),fromAddres,fromAddres);     
            }
            }
        }
        else
        {
            DataTable userTemplate = new Suryani.Commerce.Core.Manager.TemplateManager().GetCustomerEmailTemplateForHoldOrderReport(USER_TEMPLATE_NAME);
            string trackingNumber = new Suryani.Commerce.Core.Shipping_Mgmt.ShipmentData().GetTrackingNumberByShipmentId(shipmentId);
            if (userTemplate != null && userTemplate.Rows.Count > 0)
            {
                subject = string.Format(userTemplate.Rows[0]["Subject"].ToString(), orderId.ToString(), trackingNumber);
                body = string.Format(userTemplate.Rows[0]["Body"].ToString(), orderId, trackingNumber);
            }
        }
        if (!string.IsNullOrEmpty(subject) && !string.IsNullOrEmpty(body) && !string.IsNullOrEmpty(from))
        {
            new MailManager().BeginInvoiceSend(from, email, string.Format("{0}\\{1}", templatePath, fileName), subject, body);
            return true;
        }
        return false;
    }

    public string GenerateClaimsInvoice(int orderId, string templatePath, string filePath, string filename)
    {
        if (orderId != -1)
        {
            CatalogID = GetOrderCatalog(orderId);
            SentTime = 1;
            //get catalog info
            DataTable catalog = new CatalogManager().GetAllCatalog();
            DataRow[] row = catalog.Select("CatalogId='" + CatalogID + "'");
            string contractPhoneInfo = row[0]["AddressToName"].ToString() + ": " + row[0]["ShipperPhone"].ToString();
            string catalogName = row[0]["catalogName"].ToString();

            string fileName = filename;
            //sendResultLable.InnerText = "";
            Suryani.Commerce.Core.Order_Mgmt.Order order = new Suryani.Commerce.Core.Order_Mgmt.Order_Manager().GetOrder(orderId);
            string trackingNumber = string.Empty;
            bool isNotPaid = CheckPOOrderPaid(order);
            if (order != null && order.OrderItems != null && order.OrderItems.Rows.Count > 0)
            {
                Document document = null;
                FileStream invoicePdfStream = null;
                PdfCopy copy = null;
                PdfReader template1 = null;
                PdfReader template2_1 = null;
                PdfReader template2_2 = null;
                PdfStamper stamper = null;
                AcroFields fields = null;
                try
                {
                    document = new Document();
                    invoicePdfStream = new FileStream(string.Format("{0}\\{1}", filePath, fileName), FileMode.Create);
                    copy = new PdfCopy(document, invoicePdfStream);
                    copy.SetFullCompression();
                    copy.CloseStream = true;
                    document.Open();
                    //judge orderitems first,if the num of orderItems less than 16,we use template1
                    //or we use template 2_1(29 rows) and template 2_2(15 rows), and how many template 2_1 will used result with this num.
                    if (order.OrderItems.Rows.Count <= 16)
                    {
                        template1 = GetTemplateByCatalogId(templatePath, 1);
                        MemoryStream invoiceStream = new MemoryStream();
                        stamper = new PdfStamper(template1, invoiceStream);
                        stamper.SetFullCompression();
                        fields = stamper.AcroFields;
                        if (order.OrderShippings != null && order.OrderShippings.Length > 0)
                        {
                            FillBillToAndShipTo(order, fields, contractPhoneInfo, "", SentTime);
                            //Order List
                            int rowIndex = 0;
                            foreach (DataRow orderItem in order.OrderItems.Rows)
                            {
                                FillOneOrderItem(fields, rowIndex, orderItem);
                                rowIndex++;
                            }
                            FillTotal(order, fields,catalogName,"");
                        }
                        stamper.FormFlattening = true;
                        stamper.Close();
                        template1 = new PdfReader(invoiceStream.ToArray());
                        template1.RemoveUnusedObjects();
                        copy.AddPage(copy.GetImportedPage(template1, 1));
                    }
                    else
                    {
                        template2_1 = GetTemplateByCatalogId(templatePath, 2);
                        template2_2 = GetTemplateByCatalogId(templatePath, 3);
                        int template2_1Num = order.OrderItems.Rows.Count / 29;
                        bool isNeedReserve = false;
                        if (order.OrderItems.Rows.Count % 29 > 15)
                        {
                            template2_1Num += 1;
                            isNeedReserve = true;
                        }
                        if (order.OrderItems.Rows.Count % 29 == 0)
                        {
                            isNeedReserve = true;
                        }
                        int totalItemsOfTemp2_1 = order.OrderItems.Rows.Count;
                        if (isNeedReserve)
                        {
                            totalItemsOfTemp2_1 -= 2;
                        }
                        for (int i = 0; i < template2_1Num; i++)  //how many template2_1 will used
                        {
                            template2_1 = GetTemplateByCatalogId(templatePath, 2);
                            MemoryStream template2_1InvoiceStream = new MemoryStream();
                            stamper = new PdfStamper(template2_1, template2_1InvoiceStream);
                            stamper.SetFullCompression();
                            //begin to fill fields
                            fields = stamper.AcroFields;
                            if (order.OrderShippings != null && order.OrderShippings.Length > 0)
                            {
                                FillBillToAndShipTo(order, fields, contractPhoneInfo, "",SentTime);
                                //Order List
                                int rowIndex = 0;
                                int pageNst = i * 29;
                                for (int j = i * 29; j < (pageNst + 29) && j < totalItemsOfTemp2_1; j++)
                                {
                                    DataRow orderItem = order.OrderItems.Rows[j];
                                    FillOneOrderItem(fields, rowIndex, orderItem);
                                    rowIndex++;
                                }
                                fields.SetField("CurrentPage", (i + 1).ToString());
                                fields.SetField("TotalPage", (template2_1Num + 1).ToString());
                            }
                            stamper.FormFlattening = true;
                            stamper.Close();
                            template2_1 = new PdfReader(template2_1InvoiceStream.ToArray());
                            template2_1.RemoveUnusedObjects();
                            copy.AddPage(copy.GetImportedPage(template2_1, 1));
                        }
                        //one template2_2 will used
                        MemoryStream template2_2InvoiceStream = new MemoryStream();
                        stamper = new PdfStamper(template2_2, template2_2InvoiceStream);
                        stamper.SetFullCompression();
                        fields = stamper.AcroFields;
                        if (order.OrderShippings != null && order.OrderShippings.Length > 0)
                        {
                            FillBillToAndShipTo(order, fields, contractPhoneInfo, "", SentTime);
                            //Order List
                            if (order.OrderItems.Rows.Count % 29 <= 15 && order.OrderItems.Rows.Count % 29 > 0)
                            {
                                int rowIndex = order.OrderItems.Rows.Count % 29 - 1;
                                int lastRowIndex = order.OrderItems.Rows.Count - 1;
                                if (rowIndex >= 0)
                                {
                                    for (int k = rowIndex; k >= 0; k--)
                                    {
                                        DataRow orderItem = order.OrderItems.Rows[lastRowIndex];
                                        FillOneOrderItem(fields, rowIndex, orderItem);
                                        rowIndex--;
                                        lastRowIndex--;
                                    }
                                }
                            }
                            else  //reserve 2 records for InvoiceTemplate2_2
                            {
                                int rowIndex = 0;
                                for (int i = order.OrderItems.Rows.Count - 2; i < order.OrderItems.Rows.Count; i++)
                                {
                                    DataRow orderItem = order.OrderItems.Rows[i];
                                    FillOneOrderItem(fields, rowIndex, orderItem);
                                    rowIndex++;
                                }
                            }
                            fields.SetField("CurrentPage", (template2_1Num + 1).ToString());
                            fields.SetField("TotalPage", (template2_1Num + 1).ToString());
                            FillTotal(order, fields,catalogName,"");
                        }
                        stamper.FormFlattening = true;
                        stamper.Close();
                        template2_2 = new PdfReader(template2_2InvoiceStream.ToArray());
                        template2_2.RemoveUnusedObjects();
                        copy.AddPage(copy.GetImportedPage(template2_2, 1));
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                finally
                {
                    document.Close();
                    if (invoicePdfStream != null)
                    {
                        invoicePdfStream.Close();
                    }
                    if (template1 != null)
                    {
                        template1.Close();
                    }
                    if (template2_1 != null)
                    {
                        template2_1.Close();
                    }
                    if (template2_2 != null)
                    {
                        template2_2.Close();
                    }
                }
            }
            else
            {
                throw new Exception("No order item to print.");
            }
        }
        return "";
    }

    private int GetOrderCatalog(int orderId)
    {
        Order order = new Order_Manager().GetOrder(orderId);
        if (order != null)
        {
            return order.PlacedCatalogId;
        }
        return 1;
    }
    private int GetPoOrderInvoiceTimes(int orderId)
    {
        int times = 1;
        times = new Order_Manager().GetPoInvoiceTimes(orderId);
        return times;
    }

    /// <summary>
    /// Harry on Dec/22/2010
    /// if catalogID = 1, then diapers template
    /// if catalogID = 2, then soap template
    /// if catalogID = 3, then bb template
    /// if whichTemplate = 1, use template 1
    /// if whichTemplate = 2, use template 2_1
    /// if whichtemplate = 3, use template 2_2
    /// </summary>
    /// <param name="templatePath"></param>
    /// <param name="whichTemplate"></param>
    /// <returns></returns>
    private PdfReader GetTemplateByCatalogId(string templatePath, int whichTemplate)
    {
        PdfReader pdfReader = null;
        string templateName = string.Empty;
        if (CatalogID == 1)
        {
            if (whichTemplate == 1)
            {
                templateName = "InvoiceTemplate1_Diapers.pdf";
            }
            else if (whichTemplate == 2)
            {
                templateName = "InvoiceTemplate2_1_Diapers.pdf";
            }
            else if (whichTemplate == 3)
            {
                templateName = "InvoiceTemplate2_2_Diapers.pdf";
            }
        }
        else if (CatalogID == 2)
        {
            if (whichTemplate == 1)
            {
                templateName = "InvoiceTemplate1_Soap.pdf";
            }
            else if (whichTemplate == 2)
            {
                templateName = "InvoiceTemplate2_1_Soap.pdf";
            }
            else if (whichTemplate == 3)
            {
                templateName = "InvoiceTemplate2_2_Soap.pdf";
            }
        }
        else if (CatalogID == 3)
        {
            if (whichTemplate == 1)
            {
                templateName = "InvoiceTemplate1_BeautyBar.pdf";
            }
            else if (whichTemplate == 2)
            {
                templateName = "InvoiceTemplate2_1_BeautyBar.pdf";
            }
            else if (whichTemplate == 3)
            {
                templateName = "InvoiceTemplate2_2_BeautyBar.pdf";
            }
        }
        else if (CatalogID == 4)
        {
            if (whichTemplate == 1)
            {
                templateName = "InvoiceTemplate1_Wag.pdf";
            }
            else if (whichTemplate == 2)
            {
                templateName = "InvoiceTemplate2_1_Wag.pdf";
            }
            else if (whichTemplate == 3)
            {
                templateName = "InvoiceTemplate2_2_Wag.pdf";
            }
        }
        else if (CatalogID == 5)
        {
            if (whichTemplate == 1)
            {
                templateName = "InvoiceTemplate1_Yoyo.pdf";
            }
            else if (whichTemplate == 2)
            {
                templateName = "InvoiceTemplate2_1_Yoyo.pdf";
            }
            else if (whichTemplate == 3)
            {
                templateName = "InvoiceTemplate2_2_Yoyo.pdf";
            }
        }
        else if(CatalogID==6)
        {
            if(whichTemplate==1)
            {
                templateName = "InvoiceTemplate1_Casa.pdf";
            }
            else if(whichTemplate==2)
            {
                templateName = "InvoiceTemplate2_1_Casa.pdf";
            }
            else if(whichTemplate==3)
            {
                templateName = "InvoiceTemplate2_2_Casa.pdf";
            }
        }
        pdfReader = new PdfReader(string.Format("{0}\\" + templateName, templatePath));
        return pdfReader;
    }

    private DataTable GetInvoiceTemplate(int catalogID)
    {
        DataTable customerTemplate = null;
        if (catalogID == 1)
        {
            customerTemplate = new Suryani.Commerce.Core.Manager.TemplateManager().GetCustomerEmailTemplateForHoldOrderReport(DIAPERS_CUSTOMER_TEMPLATE_NAME);
        }
        else if (catalogID == 2)
        {
            customerTemplate = new Suryani.Commerce.Core.Manager.TemplateManager().GetCustomerEmailTemplateForHoldOrderReport(SOAP_CUSTOMER_TEMPLATE_NAME);
        }
        else if (catalogID == 3)
        {
            customerTemplate = new Suryani.Commerce.Core.Manager.TemplateManager().GetCustomerEmailTemplateForHoldOrderReport(BEAUTYBAR_CUSTOMER_TEMPLATE_NAME);
        }
        else if (catalogID == 4)
        {
            customerTemplate = new Suryani.Commerce.Core.Manager.TemplateManager().GetCustomerEmailTemplateForHoldOrderReport(WAG_CUSTOMER_TEMPLATE_NAME);
        }
        else if (catalogID == 5)
        {
            customerTemplate = new Suryani.Commerce.Core.Manager.TemplateManager().GetCustomerEmailTemplateForHoldOrderReport(YOYO_CUSTOMER_TEMPLATE_NAME);
        }
        else if (catalogID == 6)
        {
            customerTemplate = new Suryani.Commerce.Core.Manager.TemplateManager().GetCustomerEmailTemplateForHoldOrderReport(CASA_CUSTOMER_TEMPLATE_NAME);
        }
        return customerTemplate;
    }
}

 

转载于:https://www.cnblogs.com/scottpei/archive/2012/04/11/2442785.html

2017-07-29 10:45:00 weixin_33811539 阅读数 6

 

 

 

 

 

Spire.PDF组件概述

Spire.PDF是一个专业的PDF组件,用于在.NET应用程序中创建,编辑,处理和阅读PDF文档。支持丰富的PDF文档处理操作,如PDF文档合并/拆分、转换(如HTML转PDF,PDF转图片等)、打印(包括静默打印)、压缩、添加/修改/删除书签、添加注释、安全设置(包括数字签名)、创建与填充域、图片插入与提取、文本提取与高亮等。它不依赖Adobe Acrobat,因此运行环境无需安装Adobe Reader或其他类似组件。 该组件分为商业版和免费版(不是试用版)两种,一般个人使用或者操作的PDF文档不超过10页时,可以使用免费版。

 

添加、修改和删除PDF书签的实现

一、添加书签

1.1 添加书签

在Spire.PDF中,每个PDF文档都有一个书签列表(PdfBookmarkCollection)。我们可以通过PdfDocument对象的Bookmarks属性来获取该列表,然后通过Add () 方法将书签添加到列表中。

//新建PDF文档

PdfDocument pdf = new PdfDocument();

//添加页面

PdfPageBase page = pdf.Pages.Add();

//添加书签
PdfBookmark bookmark = pdf.Bookmarks.Add("第一页");

//设置书签所指向的页面和位置,(0,0)表示页面的开始位置

bookmark.Destination = new PdfDestination(page);
bookmark.Destination.Location = new PointF(0, 0);

//设置书签的文本格式和颜色

bookmark.DisplayStyle = PdfTextStyle.Bold;
bookmark.Color = Color.Black;

//保存文档

pdf.SaveToFile("Bookmark2.pdf");

1.2 添加子书签

添加子书签和添加普通书签的方式基本一样,不同的是普通书签是直接添加到文档的书签列表里,而子书签则是添加到父书签的列表里。

//新建PDF文档

PdfDocument pdf = new PdfDocument();

//添加页面

PdfPageBase page = pdf.Pages.Add(); 

//添加书签

PdfBookmark bookmark = pdf.Bookmarks.Add("第一章 热传导");

//设置书签指向的页面和位置

bookmark.Destination = new PdfDestination(page);
bookmark.Destination.Location = new PointF(0, 0);
 
//设置书签的文本格式和颜色

bookmark.DisplayStyle = PdfTextStyle.Bold;
bookmark.Color = Color.SeaGreen;

//添加子书签

PdfBookmark childBookmark = bookmark.Insert(0, "1.1 热传导基本知识");

//设置子书签指向的页面和位置

childBookmark.Destination = new PdfDestination(page);
childBookmark.Destination.Location = new PointF(400, 300);

//设置子书签的文本格式和颜色

childBookmark.DisplayStyle = PdfTextStyle.Regular;
childBookmark.Color = Color.Black;

//保存文档

pdf.SaveToFile("ChildBookmark.pdf");

 

 

1.3 添加书签到现有文档

除了在新建的PDF文档里添加书签,我们还可以给现有的PDF文档添加书签。加载PDF文档的方法除LoadFromFile以外,还有LoadFromStream (从流加载),LoadFromHTML(从HTML加载)等,可根据自己的需求选择相应的加载方式。

//加载文档

PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("示例.pdf"); 

for (int i = 0; i < pdf.Pages.Count; i++)
{
    //添加书签

    PdfBookmark bookmark = pdf.Bookmarks.Add(string.Format("第{0}章", i+1));

    //设置书签指向的页面和位置

    bookmark.Destination = new PdfDestination(pdf.Pages[i]);
    bookmark.Destination.Location = new PointF(0, 0);

    //设置书签的文本格式和颜色

    bookmark.DisplayStyle = PdfTextStyle.Bold;
    bookmark.Color = Color.Black;
}

//保存文档

pdf.SaveToFile("Bookmark2.pdf");

 

 

2. 修改书签

Spire.PDF支持多种书签修改方式,例如修改现有书签的内容,插入新书签到现有书签列表,插入子书签到现有书签等。这里我选取修改书签内容和插入新书签到现有书签列表进行介绍。

2.1 修改现有书签内容

//加载文档

PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("Bookmark2.pdf");

//获取书签列表

PdfBookmarkCollection bookmarks = pdf.Bookmarks;

//获取第一个书签

PdfBookmark bookmark = bookmarks[0];

//修改书签指向的页面

bookmark.Destination = new PdfDestination(document.Pages[1]); 

//修改书签的文本格式和颜色

bookmark.DisplayStyle = PdfTextStyle.Bold;
bookmark.Color = Color.Green;

//修改书签的title

bookmark.Title = "修改";

//保存文档

pdf.SaveToFile("ModifyBookmark.pdf");

 

2.2 插入新书签到现有书签列表

//加载文档
 
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("Bookmark2.pdf");
 
//插入新书签到指定位置(此处插入的是第三个书签的位置)
 
PdfBookmark bookmark = pdf.Bookmarks.Insert(2, "新增第三章");
 
//设置书签所指向的页面和位置
 
bookmark.Destination = new PdfDestination(document.Pages[1]);
bookmark.Destination.Location = new PointF(0, 300);
 
//保存文档
 
pdf.SaveToFile("InsertBookmark.pdf");

 

 

3. 删除书签

删除书签时,可以使用书签的序号,也可以使用书签的名称。这里我使用的是序号的方式。

//加载文档

PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("Bookmark2.pdf");

//获取书签列表

PdfBookmarkCollection bookmarks = document.Bookmarks;

//删除第一个书签

bookmarks.RemoveAt(0);

//保存文档

pdf.SaveToFile("DeleteBookmark.pdf");

 

 

转自:http://www.cnblogs.com/Yesi/p/7251214.html

 

2009-08-12 15:09:00 beimuaihui 阅读数 590

1.使用iTextSharp ,可以添加水印,图片

 

2.GhostScript 将pdf生成图片

c#操作pdf的类库

阅读数 1203

C#生成(操作)PDF

阅读数 9

C#操作PDF总结

阅读数 7501

c# 操作excel生成pdf

阅读数 2303

没有更多推荐了,返回首页