.netcore 操作aspose.words导出pdf

个人重点关注的是生成曲线图的部分,浪费了我很多时间

chart.Legend.Position = LegendPosition.Top; 

控制图形的显示位置,这个地方好像必须要选一个位置,否则会内容显示不全,我开始用的LegendPosition.None,他就显示不了那几条线的颜色和名称说明文字。为了搞出这个效果浪费了我一天时间。

.netcore 操作aspose.words导出pdf_第1张图片

 

xAxis.Hidden = true;//隐藏x轴标签

public class ExpReport
{
    //IWebHostEnvironment _webHostEnvironment;

    //public ExpReport(IWebHostEnvironment webHostEnvironment)
    //{
    //    _webHostEnvironment = webHostEnvironment;
    //}
 
    public static string ReportChartPdf(List Listdto, ExpReportDto ReportDto)
    {
        try
        {
            IConfiguration myconfiguration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build();

            Document doc = new Document();

            DocumentBuilder builder = new DocumentBuilder(doc);
            
            builder.PageSetup.Orientation = Orientation.Portrait;

            //var parentPath = AppContext.BaseDirectory.ToString()+@"\wwwroot\";
            var parentPath = Path.Combine(IOCProvider.GetService().ContentRootPath,"wwwroot"); 
            //
            string strReportFileUrl = myconfiguration["Report:ReportFileUrl"].ToString();
            string dateDir = DateTime.Now.Date.ToString("yyyyMMdd");
            string saveFileStr = "温湿度曲线报表_" + DateTime.Now.Date.ToString("yyyyMMddHHmmss") + new Random().Next(1, 1000).ToString() + ".docx";
            // 你用path

             
            string strSavePath = Path.Combine(parentPath, strReportFileUrl, dateDir);
            FolderAndFile.FolderCreate(strSavePath);

            strSavePath = Path.Combine(strSavePath, saveFileStr);  


            string strCompanyLogo = myconfiguration["Report:CompanyLogo"].ToString();  
            string Logpicurl =  Path.Combine(parentPath, strCompanyLogo);


            string ComLogoWidth = myconfiguration["Report:CompanyLogoWidth"].ToString();
            string ComLogoHeight = myconfiguration["Report:CompanyLogoHeight"].ToString();
            //Logpicurl = FolderAndFile.SetImageSize(float.Parse(ComLogoWidth), float.Parse(ComLogoHeight), Logpicurl, "");


            string RepImageWidth = myconfiguration["Report:ReportImageWidth"].ToString();
            string RepImageHeight = myconfiguration["Report:ReportImageHeight"].ToString();
       

            
            ReportDto.LogoPicUrl = Logpicurl;
            ReportDto.aveWD = Math.Round((decimal)Listdto.Average(x => x.wd1), 1).ToString("0.0");
            ReportDto.aveSD = Math.Round((decimal)Listdto.Average(x => x.sd1), 1).ToString("0.0");
            ReportDto.highWD = Listdto.Max(x => (decimal)x.wd1).ToString("0.0");
            ReportDto.highSD = Listdto.Max(x => (decimal)x.sd1).ToString("0.0");
            ReportDto.lowWD = Listdto.Min(x => (decimal)x.wd1).ToString("0.0");
            ReportDto.lowSD = Listdto.Min(x => (decimal)x.sd1).ToString("0.0");
            ReportDto.WDLimit = ((decimal)Listdto[0].wdlowLimit).ToString("0.0") + "--" + ((decimal)Listdto[0].wdHghLimit).ToString("0.0");
            ReportDto.SDLimit = ((decimal)Listdto[0].sdLowLimit).ToString("0.0") + "--" + ((decimal)Listdto[0].sdHghLimit).ToString("0.0");
            var alarmList = Listdto.Select(x => new { x.wd1, x.sd1, x.dt }).Where(x => x.wd1 < ((decimal)Listdto[0].wdlowLimit) || x.wd1 > ((decimal)Listdto[0].wdHghLimit) || x.sd1 < ((decimal)Listdto[0].sdLowLimit) || x.sd1 > ((decimal)Listdto[0].sdHghLimit));
            ReportDto.alarmCount = alarmList.Count().ToString();
            var alarmArry = alarmList.Take(20).Select(x => new { x.wd1, x.dt }.ToString()).ToArray();
            alarmArry = (from a in alarmList
                         select "温度:" + a.wd1 + " 湿度:" + a.sd1 + " 时间:" + a.dt.ToString("yyyy-MM-dd HH:mm:ss") + "").Take(20).ToArray();
            ReportDto.alarmData = string.Join(" , ", alarmArry);
            

            builder.InsertImage(Logpicurl, RelativeHorizontalPosition.Margin, 1, RelativeVerticalPosition.Margin, 1, double.Parse(ComLogoWidth), double.Parse(ComLogoHeight), WrapType.Square);

            for (int i = 0; i < 10; i++)
            {
                builder.InsertBreak(BreakType.LineBreak); 
            }

            for (int i = 0; i < 3; i++)
            {
                builder.InsertBreak(BreakType.LineBreak);
            }

            ParagraphFormat paragraphFormat = builder.ParagraphFormat;
            paragraphFormat.Alignment = ParagraphAlignment.Center; 
            builder.Font.Size = 18;
            builder.Font.Name = "Arial";
            builder.Font.Bold = false;
            //paragraphFormat.FirstLineIndent = 8;
            //paragraphFormat.Alignment = ParagraphAlignment.Center;
            //paragraphFormat.KeepTogether = true;
            //builder.Writeln($"时间区间:{ReportDto.StartTime} 到 {ReportDto.EndTime}");

            builder.CellFormat.ClearFormatting(); 

            for (int i = 0; i < 5; i++)
            {
                builder.InsertBreak(BreakType.LineBreak); 
            }

            builder.Font.Size = 35;
            builder.Font.Bold = true;
            builder.Writeln("温湿度报表");
            builder.Font.Size = 20;
            builder.Font.Bold = false;
            builder.Writeln($"报告人:{ReportDto.ReportMan} 制表人:{ReportDto.CreateManBottom}");
            builder.Writeln($"时间:{ReportDto.ReportTime}");
            

            builder.InsertBreak(BreakType.SectionBreakNewPage); 
            builder.PageSetup.Orientation = Orientation.Landscape; 


            builder.StartTable(); 

            builder.CellFormat.ClearFormatting(); 
            builder.ParagraphFormat.Alignment = ParagraphAlignment.Left; 
            builder.CellFormat.Width = builder.PageSetup.PageWidth - 140; 
            builder.Font.Size = 15;
            builder.Font.Name = "Arial";
            builder.Font.Bold = true;

            builder.InsertCell();
            builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
            builder.Write($"{ReportDto.eqno}--温湿度\r\n");
            builder.EndRow();


            builder.InsertCell();
            builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;
            builder.Font.Size = 15;
            builder.Font.Name = "Arial";
            builder.Font.Bold = true;
            builder.Writeln("监测对象描述");
            builder.Write("\r\n");
            builder.Font.Name = "宋体";
            builder.Font.Bold = false;
            builder.Writeln($"\t监测对象名称:{ReportDto.Testname}");
            builder.Write("\r\n");
            builder.Writeln($"\t监测条件:{ReportDto.Condition}");
            builder.Write("\r\n");
            builder.Writeln($"\t监测对象类型:{ReportDto.Testboxtype}");
            builder.Write("\r\n");
            builder.Writeln($"\t监测对象编号:{ReportDto.Testboxno}");
            builder.Write("\r\n");
            builder.Writeln($"\t监测对象批号:{ReportDto.Pihao}");
            builder.Write("\r\n");
            //builder.EndRow();

            //builder.InsertCell();
            builder.Font.Name = "Arial";
            builder.Font.Bold = true;
            builder.Writeln("各项统计");
            builder.Write("\r\n");
            builder.Font.Name = "宋体";
            builder.Font.Bold = false;
            builder.Writeln($"\t平均温度:{ReportDto.aveWD}  最高温度:{ReportDto.highWD}   最低温度:{ReportDto.lowWD}  设定门限:{ReportDto.WDLimit}");
            builder.Write("\r\n");
            builder.Writeln($"\t平均湿度:{ReportDto.aveSD}  最高湿度:{ReportDto.highSD}   最低湿度:{ReportDto.lowSD}  设定门限:{ReportDto.SDLimit}");
            builder.Write("\r\n");
            builder.Writeln($"\t温度告警总数:{ReportDto.alarmCount}");
            builder.Write("\r\n");
            builder.Write("\r\n"); 
            builder.EndRow();



            builder.InsertCell();
            paragraphFormat = builder.ParagraphFormat;
            paragraphFormat.Alignment = ParagraphAlignment.Center;//居中
            builder.Font.Size = 15;
            builder.Font.Name = "Arial";
            builder.Font.Bold = true;
            builder.Writeln($"\t时间区间:{ReportDto.StartTime} 到 {ReportDto.EndTime}");
            builder.Write("\r\n");
            //builder.Writeln("温度曲线图(横轴:时间;纵轴:温度、湿度)");

            
            Shape shape = builder.InsertChart(ChartType.Line, double.Parse(RepImageWidth) + 80, double.Parse(RepImageHeight)+100);
            shape.FillColor = Color.Transparent;//背景透明
             

            var chart = shape.Chart;
            chart.Title.Text = "温湿度曲线图(横轴:时间;纵轴:温度、湿度)";
            chart.Title.Show = true; 
            chart.Series.Clear();
            chart.Legend.Position = LegendPosition.Top;

            var dataTimeList = Listdto.Select(x => x.dt.ToString("yyyy-MM-dd HH:mm:ss")).ToList();
            var dataList = Listdto.Select(x => Convert.ToDouble(x.wd1)).ToList();
            var dataListwdlowlimit = Listdto.Select(x => Convert.ToDouble(x.wdlowLimit)).ToList();
            var dataListwdhghlimit = Listdto.Select(x => Convert.ToDouble(x.wdHghLimit)).ToList();
            var series_wd = chart.Series.Add("温度",
               dataTimeList.ToArray(),
               dataList.ToArray());
            //series_wd.Name = "温度";
            series_wd.Marker.Symbol = MarkerSymbol.Circle;
            series_wd.Marker.Size = 3;
            //series_wd. = "";


            //series = chart.Series.Add("wd1",
            // dataTimeList.ToArray(),
            // dataList.ToArray());

            var series_wdlow = chart.Series.Add("温度下限",
            dataTimeList.ToArray(),
            dataListwdlowlimit.ToArray());
            //series_wdlow.Name = "温度下限";
            series_wdlow.Marker.Symbol = MarkerSymbol.Circle;
            series_wdlow.Marker.Size = 2;

            var series_wdhgh = chart.Series.Add("温度上限",
            dataTimeList.ToArray(),
            dataListwdhghlimit.ToArray());
            //series_wdhgh.Name = "温度上限";
            series_wdhgh.Marker.Symbol = MarkerSymbol.Circle;
            series_wdhgh.Marker.Size =2;



            //dataTimeList = Listdto.Select(x => x.dt.ToString("yyyy-MM-dd HH:mm:ss")).ToList();
            dataList = Listdto.Select(x => Convert.ToDouble(x.sd1)).ToList();
            var dataListsdlowlimit = Listdto.Select(x => Convert.ToDouble(x.sdLowLimit)).ToList();
            var dataListsdhghlimit = Listdto.Select(x => Convert.ToDouble(x.sdHghLimit)).ToList();
            var series_sd = chart.Series.Add("sd1",
               dataTimeList.ToArray(),
               dataList.ToArray());
            series_sd.Name = "湿度";
            series_sd.Marker.Symbol = MarkerSymbol.Circle;
            series_sd.Marker.Size = 3;

            var series_sdlow=chart.Series.Add("sdlowlimit",
               dataTimeList.ToArray(),
               dataListsdlowlimit.ToArray());
            series_sdlow.Name = "湿度下限";
            series_sdlow.Marker.Symbol = MarkerSymbol.Circle;
            series_sdlow.Marker.Size = 2;

            var series_sdhgh = chart.Series.Add("sdhghlimit",
               dataTimeList.ToArray(),
               dataListsdhghlimit.ToArray());
            series_sdhgh.Name = "湿度上限";
            series_sdhgh.Marker.Symbol= MarkerSymbol.Circle;
            series_sdhgh.Marker.Size = 2;




            ChartDataPointCollection dataPoints = series.DataPoints;
            默认给每个数据点样式
            series.InvertIfNegative = true;
            //chart.Series[0].Marker.Symbol = MarkerSymbol.Circle;
            //chart.Series[0].Marker.Size = 5;
            //chart.Series[0].Name = "温度曲线图";

            ChartAxis xAxis = chart.AxisX;
            xAxis.TickLabelSpacingIsAuto = true;
            xAxis.Hidden = true;//隐藏x轴标签


            ChartAxis yAxis = chart.AxisY;


            yAxis.TickLabelPosition = AxisTickLabelPosition.NextToAxis;//坐标轴位置


            paragraphFormat = builder.ParagraphFormat;
            paragraphFormat.Alignment = ParagraphAlignment.Center;//居中
            builder.Font.Size = 12;
            builder.Font.Name = "Arial";
            builder.Font.Bold = true;
            builder.Font.Color = Color.Red;
            builder.Writeln("本图形时间顺序是从左到右");
            builder.EndRow();

            //builder.InsertCell();
            //paragraphFormat = builder.ParagraphFormat;
            //paragraphFormat.Alignment = ParagraphAlignment.Center;//居中
            //builder.Font.ClearFormatting();
            //builder.Font.Size = 15;
            //builder.Font.Name = "Arial";
            //builder.Font.Bold = true;
            //builder.Writeln("绘制湿度曲线(横轴:时间;纵轴:湿度)");


            //shape = builder.InsertChart(ChartType.Line, double.Parse(RepImageWidth) + 80, double.Parse(RepImageHeight));
            //chart = shape.Chart;
            //shape.FillColor = Color.Transparent;
            //chart.Title.Text = "绘制湿度曲线(横轴:时间;纵轴:湿度)";
            //chart.Title.Show = false;
            //chart.Series.Clear();

            //chart.Legend.Position = LegendPosition.None;

            //dataTimeList = Listdto.Select(x => x.dt.ToString("yyyy-MM-dd HH:mm:ss")).ToList();
            //dataList = Listdto.Select(x => Convert.ToDouble(x.sd1)).ToList();
            //var dataListsdlowlimit = Listdto.Select(x => Convert.ToDouble(x.sdLowLimit)).ToList();
            //var dataListsdhghlimit = Listdto.Select(x => Convert.ToDouble(x.sdHghLimit)).ToList();
            //series = chart.Series.Add("sd1",
            //   dataTimeList.ToArray(),
            //   dataList.ToArray());

            //chart.Series.Add("sdlowlimit",
            //   dataTimeList.ToArray(),
            //   dataListsdlowlimit.ToArray());
            //chart.Series.Add("sdhghlimit",
            //   dataTimeList.ToArray(),
            //   dataListsdhghlimit.ToArray());

            //chart.Series[0].Marker.Symbol = MarkerSymbol.Circle;
            //chart.Series[0].Marker.Size = 5;
            //chart.Series[0].Name = "  ";

            //chart.Series[0].DataLabels.Clear();




            //xAxis = chart.AxisX;
            //xAxis.Hidden = true;

            //yAxis = chart.AxisY;

            //yAxis.TickLabelPosition = AxisTickLabelPosition.NextToAxis;


            //paragraphFormat = builder.ParagraphFormat;
            //paragraphFormat.Alignment = ParagraphAlignment.Center;//居中
            //builder.Font.Size = 12;
            //builder.Font.Name = "Arial";
            //builder.Font.Bold = true;
            //builder.Font.Color = Color.Red;
            //builder.Writeln("本图形时间顺序是从左到右");
            //builder.EndRow();


            builder.InsertCell();
            builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
            builder.Font.ClearFormatting();
            builder.Font.Name = "Arial";
            builder.Font.Size = 15;
            builder.Font.Bold = true;
            builder.Writeln($"最近20组告警数据");
            builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;//居左
            builder.Font.Name = "宋体";
            builder.Font.Bold = false;
            builder.Writeln($"{ReportDto.alarmData}");
            for (int i = 0; i < 2; i++)
            {
                builder.InsertBreak(BreakType.LineBreak);// 
            }
            builder.EndRow();

            builder.InsertCell();
            builder.Font.Name = "Arial";
            builder.Font.Size = 15;
            builder.Font.Bold = true;
            builder.Writeln($"制表人:{ReportDto.CreateMan}");
            builder.Writeln($"时   间 :{ReportDto.ReportTime}");
            builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;
            builder.Writeln($"签名:\t\t\t");
            builder.EndRow();



            builder.EndTable();
            

            var docDir = Regex.Split(strSavePath, ".docx", RegexOptions.IgnoreCase)[0] + ".docx";
            doc.Save(docDir, SaveFormat.Docx);


            Document doct = new Document(docDir);
            var pdfDir = Regex.Split(strSavePath, ".docx", RegexOptions.IgnoreCase)[0] + ".pdf";


            PdfSaveOptions saveOption = new PdfSaveOptions();
            saveOption.SaveFormat = SaveFormat.Pdf;

            var passwd = string.IsNullOrEmpty(ReportDto.passwd) ? string.Empty : ReportDto.passwd;
            PdfEncryptionDetails encryptionDetails = new PdfEncryptionDetails(passwd, "owner", PdfEncryptionAlgorithm.RC4_128);
            encryptionDetails.Permissions = PdfPermissions.DisallowAll;
            encryptionDetails.Permissions = PdfPermissions.Printing | PdfPermissions.HighResolutionPrinting;


            saveOption.EncryptionDetails = encryptionDetails;
            var saveret=  doct.Save(pdfDir, saveOption);

            string returnHtppurl = "";
            if (!string.IsNullOrEmpty(pdfDir))
            {
               
                //var myhttprequest = IOCProvider.GetService().HttpContext.Request;
                //var httpHost = myhttprequest.Scheme + "://" + myhttprequest.Host;
                //string httpHost = AppDomain.CurrentDomain.BaseDirectory;
                string FullFileName = "";
                string nowDirection = "";

                string[] fileUrlArr = pdfDir.Split('\\');
                FullFileName = fileUrlArr[fileUrlArr.Length - 1];
                nowDirection = fileUrlArr[fileUrlArr.Length - 2];


                returnHtppurl = myconfiguration["Report:ReportFileUrl"].ToString().Replace("\\", "/") + "/" + nowDirection + "/" + FullFileName;
                //returnHtppurl =  filePath;



            }
            else
            {
                
            }

            return returnHtppurl;
        }
        catch (Exception ex)
        {

            throw new Exception(ex.Message);
        }

    }
}

你可能感兴趣的:(NETCORE,abpvnext,.netcore,pdf,windows)