数据导出PDF文件

#region PDF文档生成
//调用生成PDF的方法。
WritePdf(@"D:\乱七八糟\123.pdf", NewList); 

/// <summary>
/// 在指定路径生成PDF文档。
/// </summary>
/// <param name="asSaveFilePath">PDF文档保存路径</param>
/// <param name="asList">数据集合</param>
private void WritePdf(string asSaveFilePath, List<Idea.Web.Interface.VisitCount.Type.CStat_ViewDay> asList)
{
    //创建一个新文档,纸张采用横向A4纸,距上下左右的边距均为10。
    Document document = new Document(PageSize.A4.rotate(), 10, 10, 20, 10);
    try
    {
        //不知具体用途,文件保存名,存在则覆盖,不存在则创建。
        PdfWriter.getInstance(document, new FileStream(asSaveFilePath, FileMode.Create));

        //添加页眉。
        HeaderFooter header = new HeaderFooter(new Phrase("日访问量分布 (" + myCStatInfo.StartTime.ToString("yyyy-MM-dd") + ")>(" + myCStatInfo.EndTime.ToString("yyyy-MM-dd") + ")"), false);
        document.Header = header;

        //打开文档。
        document.Open();

        //生成文档内容并写入。
        loadDocument(document, asList);
    }
    catch
    {

    }
    finally
    {
        document.Close();
    }
}

public static void loadDocument(Document document, List<Idea.Web.Interface.VisitCount.Type.CStat_ViewDay> asList)
{
    //文档列数。
    int NumColumns = 9;
    try
    {
        //创建PDF文档中的字体
        BaseFont baseFont = BaseFont.createFont(@"C:\WINDOWS\Fonts\SIMHEI.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

        //根据字体路径和字体大小属性创建字体
        Font font = new Font(baseFont, 12, Font.NORMAL);

        //创建一个指定列数的表。
        PdfPTable datatable = new PdfPTable(NumColumns);

        datatable.DefaultCell.Padding = 3;

        //指定每列的宽度。
        float[] headerwidths = { 9, 4, 8, 10, 8, 11, 9, 7, 9 };
        datatable.setWidths(headerwidths);

        //应该是总体宽度为100。
        datatable.WidthPercentage = 100; // percentage
       
        //指定表头标题的边框样式。
        datatable.DefaultCell.BorderWidth = 2;
       
        //指定表头标题的内容横向居中。
        datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
       
        //指定表头标题的内容纵向居中。
        datatable.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;
       
        //指定表头标题的内容。
        datatable.addCell(new Paragraph("日 期", font));
        datatable.addCell(new Paragraph("点击率", font));
        datatable.addCell(new Paragraph("IP", font));
        datatable.addCell(new Paragraph("独立访客", font));
        datatable.addCell(new Paragraph("新访客", font));
        datatable.addCell(new Paragraph("访问次数", font));
        datatable.addCell(new Paragraph("回访次数", font));
        datatable.addCell(new Paragraph("人均PV", font));
        datatable.addCell(new Paragraph("PV比例", font));

        //应该是指定每页是否显示表头。
        datatable.HeaderRows = 1;
       
        //指定单元格的边框宽度。
        datatable.DefaultCell.BorderWidth = 1;

        int max = asList.Count;
        Idea.Web.Interface.VisitCount.Type.CStat_ViewDay myCStat_ViewDay1 = new Idea.Web.Interface.VisitCount.Type.CStat_ViewDay();
        int ipCount = 0, pvCount = 0, cusCount = 0, newCount = 0, timCount = 0, otimCount = 0;
        for (int j = 0; j < asList.Count; j++)
        {
            ipCount += asList[j].ipCount;
            pvCount += asList[j].pvCount;
            cusCount += asList[j].cusCount;
            newCount += asList[j].newCount;
            timCount += asList[j].timCount;
            otimCount += asList[j].otimCount;
        }
        myCStat_ViewDay1.ipCount = ipCount;
        myCStat_ViewDay1.ipCount = pvCount;
        myCStat_ViewDay1.ipCount = cusCount;
        myCStat_ViewDay1.newCount = newCount;
        myCStat_ViewDay1.timCount = timCount;
        myCStat_ViewDay1.otimCount = otimCount;
        asList[0].ipCount = ipCount;
        asList[0].pvCount = pvCount;
        asList[0].cusCount = cusCount;
        asList[0].newCount = newCount;
        asList[0].timCount = timCount;
        asList[0].otimCount = otimCount;

        for (int i = 0; i < max; i++)
        {
            if (i % 2 == 1)
            {
                datatable.DefaultCell.GrayFill = 0.9f;
            }
            string riqi = "";
            if (asList[i].vYear != 0 && asList[i].vMonth != 0 && asList[i].vDay != 0)
            {
                riqi = asList[i].vYear + "年" + asList[i].vMonth + "月" + asList[i].vDay + "日";
            }
            else
            {
                riqi = "总  计";
            }

            datatable.addCell(new Paragraph(riqi.ToString(), font));
            datatable.addCell(new Paragraph(asList[i].pvCount.ToString(), font));
            datatable.addCell(new Paragraph(asList[i].ipCount.ToString(), font));
            datatable.addCell(new Paragraph(asList[i].cusCount.ToString(), font));
            datatable.addCell(new Paragraph(asList[i].newCount.ToString(), font));
            datatable.addCell(new Paragraph(asList[i].timCount.ToString(), font));
            datatable.addCell(new Paragraph(asList[i].otimCount.ToString(), font));
            datatable.addCell(new Paragraph(asList[i].AVG.ToString("0.0"), font));
            if (asList[i].pvCount != 0 && asList[0].pvCount != 0)
            {
                asList[i].Percent = (float)(Convert.ToDouble(asList[i].pvCount) / Convert.ToDouble(asList[0].pvCount)) * 100;
            }
            datatable.addCell(new Paragraph(asList[i].Percent.ToString("0.00") + "%", font));

            if (i % 2 == 1)
            {
                datatable.DefaultCell.GrayFill = 0.0f;
            }
        }
        document.Add(datatable);
    }
    catch (Exception e)
    {
        Console.Error.WriteLine(e.StackTrace);
    }
}
#endregion

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
用C#实现生成PDF文档(附源码) 收藏 //write by wenhui.org using System; using System.IO; using System.Text; using System.Collections; namespace PDFGenerator { public class PDFGenerator { static float pageWidth = 594.0f; static float pageDepth = 828.0f; static float pageMargin = 30.0f; static float fontSize = 20.0f; static float leadSize = 10.0f; static StreamWriter pPDF=new StreamWriter("E:\myPDF.pdf"); static MemoryStream mPDF= new MemoryStream(); static void ConvertToByteAndAddtoStream(string strMsg) { Byte[] buffer=null; buffer=ASCIIEncoding.ASCII.GetBytes(strMsg); mPDF.Write(buffer,0,buffer.Length); buffer=null; } static string xRefFormatting(long xValue) { string strMsg =xValue.ToString(); int iLen=strMsg.Length; if (iLen<10) { StringBuilder s=new StringBuilder(); int i=10-iLen; s.Append('0',i); strMsg=s.ToString() + strMsg; } return strMsg; } static void Main(string[] args) { ArrayList xRefs=new ArrayList(); //Byte[] buffer=null; float yPos =0f; long streamStart=0; long streamEnd=0; long streamLen =0; string strPDFMessage=null; //PDF文档头信息 strPDFMessage="%PDF-1.1 "; ConvertToByteAndAddtoStream(strPDFMessage); xRefs.Add(mPDF.Length); strPDFMessage="1 0 obj "; ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage="<> "; ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage="stream "; ConvertToByteAndAddtoStream(strPDFMessage); ////////PDF文档描述 streamStart=mPDF.Length; //字体 strPDFMessage="BT /F0 " + fontSize +" Tf "; ConvertToByteAndAddtoStream(strPDFMessage); //PDF文档实体高度 yPos = pageDepth - pageMargin; strPDFMessage=pageMargin + " " + yPos +" Td " ; ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage= leadSize+" TL " ; ConvertToByteAndAddtoStream(strPDFMessage); //实体内容 strPDFMessage= "(http://www.wenhui.org)Tj " ; ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage= "ET "; ConvertToByteAndAddtoStream(strPDFMessage); streamEnd=mPDF.Length; streamLen=streamEnd-streamStart; strPDFMessage= "endstream endobj "; ConvertToByteAndAddtoStream(strPDFMessage); //PDF文档的版本信息 xRefs.Add(mPDF.Length); strPDFMessage="2 0 obj "+ streamLen + " endobj "; ConvertToByteAndAddtoStream(strPDFMessage); xRefs.Add(mPDF.Length); strPDFMessage="3 0 obj <> endobj "; ConvertToByteAndAddtoStream(strPDFMessage); xRefs.Add(mPDF.Length); strPDFMessage="4 0 obj <</Type /Pages /Count 1 "; ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage="/Kids[ 3 0 R ] "; ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage="/Resources<</ProcSet[/PDF/Text]/Font<> >> "; ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage="/MediaBox [ 0 0 "+ pageWidth + " " + pageDepth + " ] >> endobj "; ConvertToByteAndAddtoStream(strPDFMessage); xRefs.Add(mPDF.Length); strPDFMessage="5 0 obj <> endobj "; ConvertToByteAndAddtoStream(strPDFMessage); xRefs.Add(mPDF.Length); strPDFMessage="6 0 obj <> endobj "; ConvertToByteAndAddtoStream(strPDFMessage); streamStart=mPDF.Length; strPDFMessage="xref 0 7 0000000000 65535 f "; for(int i=0;i<xRefs.Count;i++) { strPDFMessage+=xRefFormatting((long) xRefs[i])+" 00000 n "; } ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage="trailer <> "; ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage="startxref " + streamStart+" %%EOF "; ConvertToByteAndAddtoStream(strPDFMessage); mPDF.WriteTo(pPDF.BaseStream); mPDF.Close(); pPDF.Close(); } } }
要实现在 Vue 中查询数据导出 PDF 文件,你需要使用一些库来生成 PDF。这里我们使用 `jspdf` 和 `html2canvas` 库来生成 PDF 文件。 首先你需要通过 Vue.js 发送一个查询数据的请求到后端,并且接收到后端返回的数据。在前端接收到数据后,你可以使用以下方法将数据生成为 PDF 文件: ```javascript import html2canvas from 'html2canvas'; import jsPDF from 'jspdf'; ... // 假设你已经从后端接收到了数据,存储在 data 变量中 const doc = new jsPDF(); const tableRows = []; const columns = [ { title: '姓名', dataKey: 'name' }, { title: '年龄', dataKey: 'age' }, { title: '性别', dataKey: 'gender' }, ]; data.forEach(item => { tableRows.push([item.name, item.age, item.gender]); }); doc.autoTable({ head: [columns.map(c => c.title)], body: tableRows, }); // 生成 PDF 文件 html2canvas(document.querySelector('#pdf-content')).then(canvas => { const imgData = canvas.toDataURL('image/png'); const imgWidth = 210; const pageHeight = 295; const imgHeight = (canvas.height * imgWidth) / canvas.width; let heightLeft = imgHeight; let position = 0; doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight); heightLeft -= pageHeight; while (heightLeft >= 0) { position = heightLeft - imgHeight; doc.addPage(); doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight); heightLeft -= pageHeight; } doc.save('data.pdf'); }); ``` 上面的代码中,我们首先使用 `autoTable` 方法将数据渲染到 PDF 表格中,然后使用 `html2canvas` 库将页面上的内容转换为 canvas,最后使用 `addImage` 方法将 canvas 添加到 PDF 中。如果 PDF 文件内容超出一页,我们需要添加新的页面来显示全部内容,这里我们使用了一个 while 循环来实现。 需要注意的是,上面的代码中使用了 `#pdf-content` 选择器来选择需要生成 PDF 的内容,你需要在你的代码中添加一个具有该选择器的元素来包含需要导出的内容。 希望这个示例能够帮助你生成 PDF 文件
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值