ASP.NET,flexpaper,SWFTools 實現簡單的PDF顯示(三)


  上面兩篇文章都講到了pdf,但如何用C#操作pdf的生成和保存等一系列的動作就要用到Itextsharp.dll控件了。

      下面簡單的介紹一下itextsharp,因為C#中使用itextsharp這類的文章百度一大堆,這里就不多說了。

itextsharp.dll,是一個開源的在C#中用來生成PDF文檔的庫文件,不少C#愛好者用它制作出了PDF文檔生成器。使用時只需在你的C#項目中添加引入此組件即可,使用方法網上有很多,自己查閱一下。如果系統提示“沒有找到itextsharp.dll”文件,或者“缺少itextsharp.dll”等錯誤信息,您可下載本文件后,將其注冊為組件或復制到相關目錄,即可解決出錯提示!

 用itextsharp生成pdf有兩種方式:

1、pdf模板方式生成pdf文件流(這里涉及到如何制作pdf的模板問題,在ASP.NET,flexpaper,SWFTools 實現簡單的PDF顯示(四)中將講到)

 

    /// <summary>
    /// 根據模板生產pdf二進制文件
    /// </summary>
    /// <param name="TempFileName">模板文件名</param>
    /// <param name="FieldValues">字典形式數據</param>
    /// <returns></returns>
    public static byte[] CreatePDf(string TempFileName, Dictionary<string, string> FieldValues)
    {
        MemoryStream ms = new MemoryStream();
        string sourcePath = HttpContext.Current.Server.MapPath("PDF") +"\\"+ TempFileName;
        PdfReader pdfReader = new PdfReader(sourcePath);
        PdfStamper stamp = new PdfStamper(pdfReader, ms, PdfWriter.VERSION_1_5, false);
        //stamp.ViewerPreferences = PdfWriter.HideWindowUI;
        //下面這段為pdf加密設置
        //stamp.SetEncryption(PdfWriter.STRENGTH40BITS, null, null,PdfWriter.ALLOW_COPY | PdfWriter.AllowPrinting);
        //stamp.Writer.CompressionLevel = PdfStream.BEST_COMPRESSION;
        //stamp.FormFlattening = true;
        //stamp.SetFullCompression();
        //stamp.Writer.CloseStream = false;
        AcroFields fields = stamp.AcroFields;
        //字體設置
        //1、直接調用系統字體
        //BaseFont font = BaseFont.CreateFont("c:\\windows\\fonts\\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        //2、系統字體放在項目文件夾中調用
        //string fontpath = HttpContext.Current.Server.MapPath(@"~/Font");
        //BaseFont font = BaseFont.CreateFont(fontpath + "\\DroidSansFallback.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        //3、通過itext的中文支持庫調用
        BaseFont.AddToResourceSearch(HttpContext.Current.Server.MapPath("iTextAsian.dll"));
        BaseFont.AddToResourceSearch(HttpContext.Current.Server.MapPath("iTextAsianCmaps.dll"));
        BaseFont font = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
        foreach (string _key in FieldValues.Keys)
        {
            fields.SetFieldProperty(_key, "textfont", font, null);
            fields.SetField(_key, FieldValues[_key]);
        }
        stamp.FormFlattening = true;
        stamp.Close();

        byte[] array = ms.ToArray();
        ms.Close();
        return array;
    }

 

2、直接代碼方式生成pdf文件流(下面這段代碼寫的只是itextsharp的簡單應用,itextsharp的功能遠不止這些,還需深入研究......)

 

public byte[] CreatePDF_Doc(Dictionary<string, string> _ret)
        {
            MemoryStream ms = new MemoryStream();
            //加載字體文件dll
            BaseFont.AddToResourceSearch(HttpContext.Current.Server.MapPath("Bin")+"\\iTextAsian.dll");
            BaseFont.AddToResourceSearch(HttpContext.Current.Server.MapPath("Bin") + "\\iTextAsianCmaps.dll");
            BaseFont font = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);            
            itex.Font fontSize14 = new itex.Font(font, 14);
            itex.Font fontSize12 = new itex.Font(font, 12);
            itex.Font fontULine = new itex.Font(font, 14, itex.Font.UNDERLINE, itex.BaseColor.GRAY);
            itex.Font fontBlack = new itex.Font(font, 16, itex.Font.BOLD, itex.BaseColor.BLACK);
            itex.Document document = new itex.Document(itex.PageSize.A4);
            PdfWriter.GetInstance(document, ms);
            if (!document.IsOpen())
            {
                document.Open();
            }

            itex.Chunk chunk1 = new itex.Chunk("中華人民共和國", fontBlack);
            itex.Chunk chunk2 = new itex.Chunk(_ret["HGMC"], fontBlack);
            chunk2.SetUnderline(0.5f, -1.5f);
            itex.Chunk chunk3 = new itex.Chunk("海關", fontBlack);
            itex.Phrase phrase1 = new itex.Phrase();
            phrase1.Add(chunk1);
            phrase1.Add(chunk2);
            phrase1.Add(chunk3);
            itex.Chunk chunk4 = new itex.Chunk("扣留清單", fontBlack);
            itex.Paragraph paragraph1 = new itex.Paragraph(phrase1);
            paragraph1.Alignment = itex.Rectangle.ALIGN_CENTER;
            itex.Paragraph paragraph2 = new itex.Paragraph(chunk4);
            paragraph2.Alignment = itex.Element.ALIGN_CENTER;
            document.Add(paragraph1);
            document.Add(paragraph2);

            itex.Chunk chunk5 = new itex.Chunk("    根據", fontSize14);
            itex.Chunk chunk6 = new itex.Chunk(_ret["AJBH"], fontSize14);
            chunk6.SetUnderline(0.5f, -1.5f);
            itex.Chunk chunk7 = new itex.Chunk("《扣留(封存)決定書》,扣留(封存)對象列明如下:", fontSize14);
            itex.Phrase phrase2 = new itex.Phrase();
            phrase2.Add(chunk5);
            phrase2.Add(chunk6);
            phrase2.Add(chunk7);
            itex.Paragraph paragraph3 = new itex.Paragraph(phrase2);
            paragraph3.Alignment = itex.Rectangle.ALIGN_LEFT;
            //行距
            paragraph3.MultipliedLeading = 3f;
            document.Add(paragraph3);

            itex.Paragraph paragraph4 = new itex.Paragraph("  ");
            paragraph4.MultipliedLeading = 1f;
            document.Add(paragraph4);

            PdfPTable table = new PdfPTable(6);
            table.HorizontalAlignment = 1;
            table.TotalWidth = 600f;
            table.DefaultCell.HorizontalAlignment = 1;
            table.AddCell(new itex.Phrase("序號", fontSize12));
            table.AddCell(new itex.Phrase("名稱", fontSize12));
            table.AddCell(new itex.Phrase("規格", fontSize12));
            table.AddCell(new itex.Phrase("數量", fontSize12));
            table.AddCell(new itex.Phrase("單位", fontSize12));
            table.AddCell(new itex.Phrase("備注", fontSize12));
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                int j = i + 1;
                table.AddCell(j.ToString());
                table.AddCell("  ", fontSize12));
                table.AddCell(new itex.Phrase("  ", fontSize12));
                table.AddCell(new itex.Phrase("  ", fontSize12));
                table.AddCell(new itex.Phrase("  ",fontSize12));
                table.AddCell(new itex.Phrase("  ",fontSize12));
            }
            document.Add(table);

            itex.Chunk chunk8 = new itex.Chunk("扣留(封存)地點:", fontSize12);
            itex.Chunk chunk9 = new itex.Chunk(_ret["KLDZ"], fontSize12);
            chunk9.SetUnderline(0.5f, -1.5f);
            itex.Phrase phrase3 = new itex.Phrase();
            phrase3.Add(chunk8);
            phrase3.Add(chunk9);
            itex.Paragraph paragraph5 = new itex.Paragraph(phrase3);
            paragraph5.MultipliedLeading = 2f;
            paragraph5.Alignment = itex.Rectangle.ALIGN_LEFT;
            paragraph5.IndentationLeft = 55f;
            document.Add(paragraph5);

            itex.Chunk chunk10 = new itex.Chunk("當事人(代理人)簽章:己收到", fontSize12);
            itex.Chunk chunk11 = new itex.Chunk(_ret["KLNR"], fontSize12);
            chunk11.SetUnderline(0.5f, -1.5f);
            itex.Chunk chunk12 = new itex.Chunk("《扣留(封存)決定書》", fontSize12);
            itex.Phrase phrase4 = new itex.Phrase();
            phrase4.Add(chunk10);
            phrase4.Add(chunk11);
            phrase4.Add(chunk12);
            itex.Paragraph paragraph6 = new itex.Paragraph(phrase4);
            paragraph6.MultipliedLeading = 2f;
            paragraph6.Alignment = itex.Rectangle.ALIGN_LEFT;
            paragraph6.IndentationLeft = 55f;
            document.Add(paragraph6);

            itex.Chunk chunk13 = new itex.Chunk("及本《扣留(封存)清單》。", fontSize12);
            itex.Chunk chunk14 = new itex.Chunk(_ret["ZFR"], fontSize12);
            chunk14.SetUnderline(0.5f, -1.5f);
            itex.Phrase phrase5 = new itex.Phrase();
            phrase5.Add(chunk13);
            phrase5.Add(chunk14);
            itex.Paragraph paragraph7 = new itex.Paragraph(phrase5);
            paragraph7.MultipliedLeading = 2f;
            paragraph7.Alignment = itex.Rectangle.ALIGN_LEFT;
            paragraph7.IndentationLeft = 55f;
            document.Add(paragraph7);

            itex.Chunk chunk15 = new itex.Chunk("執法人員簽名:", fontSize12);
            itex.Chunk chunk16 = new itex.Chunk(_ret["JZR"], fontSize12);
            chunk16.SetUnderline(0.5f, -1.5f);
            itex.Chunk chunk17 = new itex.Chunk("見證人簽名:", fontSize12);
            itex.Chunk chunk18 = new itex.Chunk(_ret["AJBH2"], fontSize12);
            chunk18.SetUnderline(0.5f, -1.5f);
            itex.Phrase phrase6 = new itex.Phrase();
            phrase6.Add(chunk15);
            phrase6.Add(chunk16);
            phrase6.Add(chunk17);
            phrase6.Add(chunk18);
            itex.Paragraph paragraph8 = new itex.Paragraph(phrase6);
            paragraph8.MultipliedLeading = 2f;
            paragraph8.Alignment = itex.Rectangle.ALIGN_LEFT;
            paragraph8.IndentationLeft = 55f;
            document.Add(paragraph8);

            itex.Paragraph paragraph9 = new itex.Paragraph("  ");
            paragraph9.MultipliedLeading = 3f;
            document.Add(paragraph9);

            itex.Paragraph paragraph10 = new itex.Paragraph(DateTime.Now.Year + "" + DateTime.Now.Month + "" + DateTime.Now.Day + "", fontSize12);
            paragraph10.Alignment = itex.Rectangle.ALIGN_RIGHT;
            document.Add(paragraph10);

            document.Close();
            byte[] array = ms.ToArray();
#if DEBUG
            string fname = HttpContext.Current.Server.MapPath("WSTemp") + "\\扣留清單" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".PDF";
            FileStream sFile = new FileStream(fname, FileMode.CreateNew);
            sFile.Write(array, 0, array.Length);
            sFile.Close();
#endif
            return array;
        }

 

 

 

 

注:上面這兩種示例代碼中我都使用了如下的字體代碼:

BaseFont.AddToResourceSearch(HttpContext.Current.Server.MapPath("Bin")+"\\iTextAsian.dll");
      BaseFont.AddToResourceSearch(HttpContext.Current.Server.MapPath(
"Bin") + "\\iTextAsianCmaps.dll");
      BaseFont font
= BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED); 

關於這種字體在ASP.NET,flexpaper,SWFTools 實現簡單的PDF顯示(二)Itexsharp生成pdf字體問題也說過,生成的pdf在flexpaper+SWFTools結合中無法顯示,具體的原因我找了很多資料也沒有沒有答案,不過如果要顯示這種字體生成的文書也有其他的方式,這個也准備在接下來的ASP.NET,flexpaper,SWFTools 實現簡單的PDF顯示(五)涉及。不過使用這種字體有個好處就是在pdf支持中文的前提下生成最小的pdf文件流即文件。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM