千篇一律,先找到元件「iTextSharp.dll」,並且加入參考。




iTextSharp 程式引用參考如下:

using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;



//建立文件物件
Document doc = Document(); // iTextSharp.text.Document

//建立記憶體物件
MemoryStream Memory = new MemoryStream(); //System.IO
PdfWriter pdf = PdfWriter.GetInstance ( doc ,  Memory ) ;


doc.Open(); //開啟文件
//開始編輯文件內容

//加入 文字 「Hello World」,若要跳行,請使用 \n
doc.Add(new Paragraph( “Hello World” );

//加入圖片tmp.png
string imgSrc = “http://localhost/tmp.png” ;
//因Image在眾多命名空間有重覆,故在此需將完整的空間命名打出。
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance ( new Uri ( imgSrc ) );
img.ScaleToFit ( 150f , 150f ) ; //定義圖片大小
doc.Add(img);


\\加入表格
PdfPTable table = new PdfPTable( 4 ); //宣告一個一排4個Cell的表格 
table.TotalWidth = 400f;
table.LockedWidth = true;

//加入一個特別定義格式的Cell
PdfPCell header
      = new PdfPCell(
            new Phrase("Header", new Font(Font.FontFamily.HELVETICA, 28f, Font.BOLD)
     ));
header.Colspan = 4;
table.AddCell(header);

//加入四個普通文字描述的Cell
table.AddCell("1");
table.AddCell("2");
table.AddCell("3");
table.AddCell("4");

//加入特別定義格式的Cell
Font font = new Font(Font.FontFamily.HELVETICA, 28f, Font.BOLD); //定義字型
PdfPCell c1 = new PdfPCell(new Phrase("item", font));
table.AddCell(c1);
PdfPCell c2 = new PdfPCell(new Phrase("test", font));
table.AddCell(c2);

//在Cell中加入圖片,圖片iTextSharp.text.Image img
PdfPCell cellimg = new PdfPCell(img);
cellimg.Colspan = 2;
cellimg.Padding = 15f;
table.AddCell(cellimg);

doc.Add(table); //文件加入方才所定義的表格



doc.Close (); //關閉文件
//關閉文件,並停止編輯文件內容


PdfReader reader = new PdfReader(Memory.GetBuffer()); //讀取記憶體中的PDF

using ( MemoryStream mem = new MemoryStream())
{

    /*
    Encrypt PdfReader
    MemoryStream Mem
    Boolean true
    string UserPassword      設定一般使用者的密碼 123
    string OwnerPassword   設定管理者的密碼 456
    int permissions
    從上方得知可以設定兩組不同權限的密碼。

    */
 
    PdfEncryptor.Encrypt( reader, Mem , true , “123” , “456” , 1 ); //設定開啟PDF的密碼
    reader.Close () //關閉讀取器

   
    //以下為輸出PDF至瀏覽器畫面
    Response.Clear();
     Response.AddHeader("Content-Disposition", "attachment;filename=test.pdf");
     Response.ContentType = "application/octet-stream";
    Response.OutputStream.Write(Mem.GetBuffer(), 0, Mem.GetBuffer().Length);
    Response.OutputStream.Flush();
    Response.OutputStream.Close();
    Response.Flush();
    Response.End();

}




PDF呈現內容如下圖:

002pdf

001pdf

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 Jiang Ying-Fu 的頭像
    Jiang Ying-Fu

    Jiang Ying-Fu的部落格

    Jiang Ying-Fu 發表在 痞客邦 留言(0) 人氣()