C#&.Net干货分享- iTextSharp导出数据源到PDF

namespace Frame.ITextSharp
{
    /// <summary>
    /// iTextSharp导出数据源到PDF
    /// </summary>
    public static class ITextSharp_PDFHelper
    {
        /// <summary>
        /// 导出Pdf
        /// </summary>
        /// <param name="localFilePath">文件保存路径</param>
        /// <param name="dtSource">数据源</param>
        /// <param name="HorV">页面横竖(为空表示竖,有非空值为横)</param>
        public static void ExportPDF(string localFilePath, DataTable dtSource, string HorV)
        {
            iTextSharp.text.io.StreamUtil.AddToResourceSearch("iTextAsian.dll");
            iTextSharp.text.io.StreamUtil.AddToResourceSearch("iTextAsianCmaps.dll");
            BaseFont bf;
            string basepath = Application.StartupPath;
            try
            {
                bf = BaseFont.CreateFont(basepath + "\\FONTS\\STSONG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            }
            catch
            {
                bf = BaseFont.CreateFont("C:\\WINDOWS\\Fonts\\STSONG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            }
            iTextSharp.text.Font font = new iTextSharp.text.Font(bf);
            iTextSharp.text.Document pdf;
            if (string.IsNullOrEmpty(HorV))
            {
                pdf = new iTextSharp.text.Document();
            }
            else
            {
                pdf = new iTextSharp.text.Document(PageSize.A4.Rotate());
            }

            PdfPTable table = new PdfPTable(dtSource.Columns.Count);
            table.HorizontalAlignment = Element.ALIGN_CENTER;
            PdfPCell cell;
            for (int i = 0; i < dtSource.Rows.Count + 1; i++)
            {
                for (int j = 0; j < dtSource.Columns.Count; j++)
                {
                    if (i == 0)
                    {
                        cell = new PdfPCell(new Phrase(dtSource.Columns[j].ColumnName, font));
                    }
                    else
                    {
                        cell = new PdfPCell(new Phrase(dtSource.Rows[i - 1][j].ToString(), font));
                    }

                    table.AddCell(cell);
                }
            }
            using (FileStream fs = new FileStream(localFilePath, FileMode.Create, FileAccess.Write))
            {

                PdfWriter.GetInstance(pdf, fs);
                pdf.Open();
                pdf.Add(table);
                pdf.Close();
            }
        }

        /// <summary>
        /// 提取PDF文件的文本内容
        /// </summary>
        /// <param name="pdfFilepath"></param>
        /// <returns></returns>
        public static string ReadPdfContent(string pdfFilepath)
        {
            try
            {
                PdfReader pdfReader = new PdfReader(pdfFilepath);
                int numberOfPages = pdfReader.NumberOfPages;
                string pfdText = string.Empty;
                for (int i = 1; i <= numberOfPages; ++i)
                {
                    //ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
                    //pfdText += PdfTextExtractor.GetTextFromPage(pdfReader, i, strategy);
                    byte[] bufferOfPageContent = pdfReader.GetPageContent(i);
                    pfdText += Encoding.UTF8.GetString(bufferOfPageContent);
                }
                pdfReader.Close();
                return pfdText;
            }
            catch
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// 添加倾斜水印
        /// </summary>
        /// <param name="pdfStream">pdf文件流</param>
        /// <param name="iTextSharpTextWaterMarkPara">水印参数</param>
        public static MemoryStream SetPdfTextWaterMark(MemoryStream pdfStream, ITextSharpTextWaterMarkPara iTextSharpTextWaterMarkPara)
        {
            try
            {
                int span = 40;//设置垂直位移
                MemoryStream outStream = new MemoryStream();
                PdfReader pdfReader = new PdfReader(pdfStream);
                PdfStamper pdfStamper = new PdfStamper(pdfReader, outStream);
                pdfStamper.Writer.CloseStream = false;
                int total = pdfReader.NumberOfPages + 1;
                PdfContentByte content;
                BaseFont font = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\STCAIYUN.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);//华文云彩字体
                PdfGState gs = new PdfGState();
                gs.FillOpacity = iTextSharpTextWaterMarkPara.Alpha;//透明度
                int waterMarkNameLenth = iTextSharpTextWaterMarkPara.WaterMarkText.Length;
                char c;
                int rise = 0;
                string spanString = " ";//水平位移
                for (int i = 1; i < total; i++)
                {
                    rise = waterMarkNameLenth * span;
                    content = pdfStamper.GetOverContent(i);//在内容上方加水印
                    //content = pdfStamper.GetUnderContent(i);//在内容下方加水印
                    content.SetGState(gs);
                    content.BeginText();
                    content.SetColorFill(BaseColor.GREEN);
                    content.SetFontAndSize(font, iTextSharpTextWaterMarkPara.FontSize);
                    int heightNumbert = (int)Math.Ceiling((decimal)iTextSharpTextWaterMarkPara.Height / (decimal)rise);//垂直重复的次数,进一发
                    int panleWith = (iTextSharpTextWaterMarkPara.FontSize + span) * waterMarkNameLenth;
                    int widthNumber = (int)Math.Ceiling((decimal)iTextSharpTextWaterMarkPara.Width / (decimal)panleWith);//水平重复次数

                    // 设置水印文字字体倾斜 开始
                    for (int w = 0; w < widthNumber; w++)
                    {
                        for (int h = 1; h <= heightNumbert; h++)
                        {
                            int yleng = rise * h;
                            content.SetTextMatrix(w * panleWith, yleng);//x,y设置水印开始的绝对左边,以左下角为x,y轴的起点
                            for (int k = 0; k < waterMarkNameLenth; k++)
                            {
                                content.SetTextRise(yleng);//指定的y轴值处添加
                                c = iTextSharpTextWaterMarkPara.WaterMarkText[k];
                                content.ShowText(c + spanString);
                                yleng -= span;
                            }
                        }
                    }
                    content.EndText();
                }
                if (pdfStamper != null)
                    pdfStamper.Close();

                if (pdfReader != null)
                    pdfReader.Close();

                return outStream;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }


    /// <summary>
    ///
    /// </summary>
    public class ITextSharpTextWaterMarkPara
    {
        /// <summary>
        ///
        /// </summary>
        public ITextSharpTextWaterMarkPara()
        {
            Width = 0;
            Height = 0;
            XCoordinate = 0;
            YCoordinate = 0;
        }

        /// <summary>
        /// 水印文本
        /// </summary>
        public string WaterMarkText { get; set; }

        /// <summary>
        /// 透明度:0,10%,20%。。。。。90%,100%
        /// 0,0.1f,0.2f,。。。。。0.9f,1
        /// </summary>
        public float Alpha { get; set; }

        /// <summary>
        /// 旋转度数
        /// </summary>
        public float RotateDegree { get; set; }

        /// <summary>
        /// 字体大小
        /// </summary>
        public int FontSize { get; set; }

        /// <summary>
        /// PDF的左边距离
        /// </summary>
        public float Width { get; set; }

        /// <summary>
        /// PDF的上边距离
        /// </summary>
        public float Height { get; set; }

        /// <summary>
        /// X坐标
        /// </summary>
        public float XCoordinate { get; set; }

        /// <summary>
        /// Y坐标
        /// </summary>
        public float YCoordinate { get; set; }
    }
}

posted @ 2019-09-04 11:29  滑溜溜的小热浪  阅读(421)  评论(0编辑  收藏  举报