using Edu.WebApi.Filter; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Mvc; using PuppeteerSharp; using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using System.Web; namespace Edu.WebApi.Controllers.User { [Route("api/[controller]/[action]")] [ApiExceptionFilter] [ApiController] [EnableCors("AllowCors")] public class HomeController : BaseController { [HttpGet] [HttpPost] [AllowAnonymous] public string Test() { return "HK"; } /// /// 文件流下载 /// /// [HttpGet] [HttpPost] [AllowAnonymous] public FileContentResult DownloadFileForPdf(int configId, string url) { DateTime start = DateTime.Now; if (Common.Config.IsLocal == 0 && Directory.Exists("Z:")) { Console.WriteLine("AA___Yes:Z:"); Common.Plugin.LogHelper.WriteInfo(Common.Plugin.NetFileHelper.WNetAddConnection(@"fast-001\administrator", "Vt@2023..", @"\\172.16.103.126\WebFile", "Z:").ToString()); } else { Console.WriteLine("BB__No:Z:"); } Console.WriteLine("{0} DownloadFileForPdf生成pdf....", start.ToString("yyyy-MM-dd HH:mm:ss fff")); try { byte[] bytes = CreateFeatureFileByte(url, configId).Result; DateTime end = DateTime.Now; string logStr = string.Format(@"生成PDF 开始时间:{0} 结束时间:{1} ", start.ToString("yyyy-MM-dd HH:mm:ss fff"), end.ToString("yyyy-MM-dd HH:mm:ss fff")); Console.WriteLine(logStr); return File(bytes, "application/octet-stream"); } catch (Exception ex) { Common.Plugin.LogHelper.Write(ex, "DownloadFileForPdf_Config_" + configId); Console.WriteLine("DownloadFileForPdf::ex" + ex.Message); } return File(new byte[0], "application/octet-stream"); } /// /// 生成PDF /// /// /// byte[] private async Task CreateFeatureFileByte(string url, int configId) { url = HttpUtility.UrlDecode(url); var chromePath = Common.Config.ReadConfigKey("chromePath"); string featurePath = Common.Config.ReadConfigKey("FeaturePath"); string IsDownLoadChrome = Common.Config.ReadConfigKey("IsDownLoadChrome"); string headerFile = string.Format(@"{0}\\{1}_\\header_1.png", featurePath, configId); string footerFile = string.Format(@"{0}\\{1}_\\footer_1.png", featurePath, configId); string headerContent = ""; string top = "0px"; string bottom = "0px"; Console.WriteLine("headerFile::Path__" + headerFile); if (System.IO.File.Exists(headerFile)) { headerContent = string.Format(@"", ConvertImageToBase64(headerFile)); top = "92px"; Console.WriteLine("Exists___Header" + configId); } string footerContent = ""; if (System.IO.File.Exists(footerFile)) { footerContent = string.Format(@"", ConvertImageToBase64(footerFile)); bottom = "50px"; Console.WriteLine("Exists___Footer___"+configId); } List argsList = new List(); var browserOptions = new LaunchOptions { Headless = true, Args = argsList.ToArray(), }; //是否下载Chrome if (IsDownLoadChrome == "1") { var result = await new BrowserFetcher().DownloadAsync(); } else { //string path= Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ".local-chromium", "Win64-970485", "chrome-win", "UserData").Replace(@"\", @"\\"); //Console.WriteLine("path::" + path); //browserOptions.UserDataDir = path; //string newPath= Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ".local-chromium", "Win64-970485", "chrome-win", "chrome.exe").Replace(@"\", @"\\"); //Console.WriteLine("newPath::" + newPath); //browserOptions.ExecutablePath = newPath; //browserOptions.ExecutablePath = chromePath; } byte[] pdfBytes = null; using (var browser = await Puppeteer.LaunchAsync(browserOptions)) { using (var page = await browser.NewPageAsync()) { await page.GoToAsync(url); await page.WaitForTimeoutAsync(10 * 1000); pdfBytes = await page.PdfDataAsync(new PdfOptions() { PrintBackground = true, MarginOptions = new PuppeteerSharp.Media.MarginOptions() { Top = top, Bottom = bottom, Left = "0px", Right = "0px", }, DisplayHeaderFooter = true, FooterTemplate = footerContent, HeaderTemplate = headerContent, }); await browser.CloseAsync(); } } return pdfBytes; } private string ConvertImageToBase64(string url) { System.Drawing.Image file = System.Drawing.Image.FromFile(url); using (MemoryStream memoryStream = new MemoryStream()) { file.Save(memoryStream, file.RawFormat); byte[] imageBytes = memoryStream.ToArray(); return Convert.ToBase64String(imageBytes); } } } }