public async Task Echo([Remainder] string message) { var account = UserAccounts.GetAccount(Context.User); string css = "<style>\n body{\n background-color: #36393e;\n}\n h1{\n color: " + account.Color + ";\n }\n h5{\n color: blue;\n }"; string html = string.Format("\n</style>\n<h1>{0}</h1>\n<h5>bericht door {1}</h5>", message, Context.User.Username); var converter = new HtmlToImageConverter(); converter.Width = 400; converter.Height = 80; var jpgBytes = converter.GenerateImage(css + html, NReco.ImageGenerator.ImageFormat.Jpeg); await Context.Channel.SendFileAsync(new MemoryStream(jpgBytes), "echo.jpg"); /* * var embed = new EmbedBuilder(); * * embed.WithTitle("message door " + Context.User.Username); * embed.WithDescription(message); * embed.WithColor(new Color(0, 255, 0)); * embed.WithThumbnailUrl(Context.User.GetAvatarUrl()); * embed.WithCurrentTimestamp(); * * await Context.Channel.SendMessageAsync("", false, embed); */ }
public async Task Succ([Remainder] string args = "") { SocketUser target = null; var mentionedUser = Context.Message.MentionedUsers.FirstOrDefault(); if (mentionedUser == null) { await Context.Channel.SendFileAsync(dir + "succ.png"); return; } target = mentionedUser ?? Context.User; string avatarUrl = target.GetAvatarUrl(); var guildUser = (SocketGuildUser)target; string css = "<style>\n #avatar{\n position: absolute;\n top: 377px;\n left: 175px;\n z-index: 1;\n width: 65px;\n height: 65px;\n }\n body {\n margin: 0;\n }\n</style>"; string imgpath = "https://cdn.discordapp.com/attachments/464773560393662465/475988185915195402/succ_edit.png"; string body = "\n<img id=\"back\" src=\"" + imgpath + "\">\n"; string avatarhtml = "<img id=\"avatar\" src = \"" + avatarUrl + "\">"; string fullhtml = css + body + avatarhtml; var converter = new HtmlToImageConverter { Width = 375, Height = 535 }; var jpgBytes = converter.GenerateImage(fullhtml, NReco.ImageGenerator.ImageFormat.Jpeg); await Context.Channel.SendFileAsync(new System.IO.MemoryStream(jpgBytes), "succd.jpg"); }
public string RenderHtml(string html) { var htmlToImageConv = new HtmlToImageConverter(); var jpegBytes = htmlToImageConv.GenerateImage(html, ImageFormat.Jpeg); return(String.Format("data:image/png;base64,{0}", Convert.ToBase64String(jpegBytes))); }
public async Task Auction([Remainder] string arg = "") { if (!IsUserRaidLeader((SocketGuildUser)Context.User)) { return; } if (_auctionSignal) { await Context.Channel.SendMessageAsync($"**Auction already running!**"); return; } _bidCounter = 0; _auctionItemName = arg; string html = ItemGrabber.GetItemInfo(_auctionItemName); var converter = new HtmlToImageConverter { Width = 340, }; var jpgBytes = converter.GenerateImage(html, NReco.ImageGenerator.ImageFormat.Jpeg); new Task(new Action(AuctionFunction)).Start(); await Context.Channel.SendMessageAsync($"**Auction start for item: {arg} - Bid time: [{Config.bot.auctionTime}] sec.**"); await Context.Channel.SendFileAsync(new MemoryStream(jpgBytes), "itemPic.jpg"); }
private Bitmap ConvertHtmlToImage(string html) { byte[] pngBytes = new HtmlToImageConverter().GenerateImage(html, ImageFormat.Png); Bitmap bmp; using (var ms = new MemoryStream(pngBytes)) bmp = new Bitmap(ms); return(bmp); }
public async Task Color(CommandContext Context, params string[] col) { string html = string.Format("<body bgcolor=\"{0}\">", col); var converter = new HtmlToImageConverter { Width = 800, Height = 800 }; var pngBytes = converter.GenerateImage(html, ImageFormat.Png); await Context.Channel.SendFileAsync(new MemoryStream(pngBytes), "gya.png"); }
public async Task html(string color = "red") { string css = "<style>\nh1{\ncolor: " + color + ";\n}\n</style>\n"; string html = String.Format("<h1>Hello {0}!</h1>", Context.User.Username); var converter = new HtmlToImageConverter { Width = 500, Height = 70 }; var jpgBytes = converter.GenerateImage(css + html, NReco.ImageGenerator.ImageFormat.Jpeg); await Context.Channel.SendFileAsync(new MemoryStream(jpgBytes), "hello.jpg"); }
public async Task Debug() { //await Smug(); var converter = new HtmlToImageConverter { Width = 375, Height = 535 }; var jpgBytes = converter.GenerateImageFromFile("./Resources/html/succ_template.html", NReco.ImageGenerator.ImageFormat.Jpeg); await Context.Channel.SendFileAsync(new System.IO.MemoryStream(jpgBytes), "succd.jpg"); }
public async Task Hello(string color = "red") { string css = "<style>\n h1{\n color: " + color + ";\n }\n</style>"; string html = "\n<h1>woot</h1>"; var converter = new HtmlToImageConverter { Width = 80, Height = 50 }; var jpgBytes = converter.GenerateImage(css + html, NReco.ImageGenerator.ImageFormat.Jpeg); await Context.Channel.SendFileAsync(new System.IO.MemoryStream(jpgBytes), "woot.jpg"); }
public async Task HtmlTest(CommandContext Context, string color = "red") { string css = "<style>\n h1{\n color: " + color + ";\n }\n</style>\n"; string html = string.Format("<h1>ya mom gay, {0} </h1>", Context.User.Username); var converter = new HtmlToImageConverter { Width = 350, Height = 70 }; var pngBytes = converter.GenerateImage(css = html, NReco.ImageGenerator.ImageFormat.Png); await Context.Channel.SendFileAsync(new MemoryStream(pngBytes), "Hello.png"); }
public async Task Hello(string color = "#c30d0d") { string css = "<style>\n hi{\n coler: #c30d0d;\n }\n</style>\n"; string html = String.Format("<h1>HELLO {0}!</h1>", Context.User.Username); var converter = new HtmlToImageConverter { Width = 50, Height = 50 }; var jpgBytes = converter.GenerateImage(css + html, NReco.ImageGenerator.ImageFormat.Jpeg); await Context.Channel.SendFileAsync(new MemoryStream(jpgBytes), "HELLO.jpg"); }
public async Task Hello() { string css = "<style>h1{color: red;}</style>"; string html = String.Format("<h1>Hello {0}</h1>", Context.User.Username); var converter = new HtmlToImageConverter { Width = 300, Height = 70 }; var jpgBytes = converter.GenerateImage(css + html, ImageFormat.Jpeg); await Context.Channel.SendFileAsync(new MemoryStream(jpgBytes), "hello.jpg"); }
public async Task TextToImage(CommandContext Context, params string[] msg) { string message = string.Join(" ", msg); string css = "<style>\n h1{\n color: rgb(51,51,51);\n }\n</style>\n"; string html = string.Format("<h1>{0}</h1>", message); var converter = new HtmlToImageConverter { Width = 1920, Height = 600 }; var pngBytes = converter.GenerateImage(css = html, ImageFormat.Png); await Context.Channel.SendFileAsync(new MemoryStream(pngBytes), "gya.png"); }
public async Task Hello([Remainder] string arg = "") { var mentionedUser = Context.Message.MentionedUsers.FirstOrDefault(); string css = "<style>\n body{\n background-image: url(https://cdn.discordapp.com/attachments/393526436343971851/415031891268206593/Nero-text.jpg);\n }\n h1{\n color: rgb(180, 0, 0)\n }\n</style>\n"; string html = String.Format("<font size=20><h1>Welcome to Aestus, {0}</h1></font>", mentionedUser.Username); var converter = new HtmlToImageConverter { Width = 2056, Height = 1156 }; var pngBytes = converter.GenerateImage(css + html, NReco.ImageGenerator.ImageFormat.Jpeg); await Context.Channel.SendFileAsync(new MemoryStream(pngBytes), "слыш письку саси :))).jpg"); }
public void image_generator(SocketGuildUser user) { string css = "<style>\n h1{\n color:#BB0A21 ;\n border-radius:20px;\n font-family: Arial, Helvetica, sans-serif;\n font-size:150%;\n}\n</style>\n"; string html = String.Format("<body bgcolor=383838><h1>{0} Won!</h1>\n</body>", user.Username); var Convertor = new HtmlToImageConverter { Width = 280, Height = 80 }; var pngbytes = Convertor.GenerateImage(css + html, ImageFormat.Png); winimage = new MemoryStream(pngbytes); }
public async Task Hoi() { var account = UserAccounts.GetAccount(Context.User); //#36393e #2f3338 string css = "<style>\n body{\n background-color: #36393e\n}\n h1{\n color: " + account.Color + ";\n }\n"; string html = String.Format("</style>\n<h1>hello {0}!</h1>", Context.User.Username); var converter = new HtmlToImageConverter(); converter.Width = 250; converter.Height = 50; var jpgBytes = converter.GenerateImage(css + html, NReco.ImageGenerator.ImageFormat.Jpeg); await Context.Channel.SendFileAsync(new MemoryStream(jpgBytes), "Hello.jpg"); }
public void GenerateImage(Stream stream) { var converter = new HtmlToImageConverter(); if (Environment.OSVersion.Platform == PlatformID.Unix) { converter.WkHtmlToImageExeName = "wkhtmltoimage"; } using var memoryStream = new MemoryStream(); converter.GenerateImage(_bodyHtml, "png", memoryStream); memoryStream.Position = 0; using var image = Image.FromStream(memoryStream); image.Save(stream, ImageFormat.Png); }
public async Task memes(string link = "", [Remainder] string legenda = "") { try { if (Context.Channel.Id == 469200747184128009) { await Context.Message.DeleteAsync(); const int delay = 5000; var m = await this.ReplyAsync($"{Context.User.Mention}. Opa, você não pode executar o comando neste canal, por favor utilize comandos-bot:smile:!"); await Task.Delay(delay); await m.DeleteAsync(); } else { if (link.Equals("laranja")) { link = "https://i.imgur.com/LXCmEUk.png"; } if (link.Equals("jailson")) { link = " https://i.imgur.com/ebbgZ6f.jpg"; } string html = "<meta charset='utf-8'>\n<style>\n\n .img_background{\n background: url('" + link + "') no-repeat;\n width: 302px;\n height: 302px;\n z-index: 1;\n \n }\n\nh1{\n z-index: 2;\n color: #fff;\n font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;\n width: 302px;\n font-size: 18pt;\n text-transform: uppercase;\n text-shadow: 1px 3px 2px #000;\n}\n</style>\n\n<div class='img_background'>\n <center><h1>" + legenda + "</h1></center>\n</div>"; var converter = new HtmlToImageConverter { Width = 298, Height = 298 }; var jpgBytes = converter.GenerateImage(html, NReco.ImageGenerator.ImageFormat.Jpeg); await Context.Message.DeleteAsync(); await ReplyAsync($"{Context.User.Mention}"); await Context.Channel.SendFileAsync(new MemoryStream(jpgBytes), "meme_habbop.jpg"); } }catch (Exception ex) { await Context.Message.DeleteAsync(); const int delay = 5000; var m = await this.ReplyAsync($"{Context.User.Mention}. Opa, ocorreu um erro na hora de executar o comando!:x:!"); await Task.Delay(delay); await m.DeleteAsync(); } }
public async Task ImageShit([Remainder] string args = "") { const string css = "<style>\n h1{\n color: rgb(27,82,122);\n }\n</style>\n"; string html = $"<h1>{args}</h1>"; if (args == "") { html = $"<h1>Hello {Context.User.Username}</h1>"; } byte[] jpegBytes = new HtmlToImageConverter { Width = 200, Height = 70 }.GenerateImage(css + html, ImageFormat.Jpeg); await Context.Channel.SendFileAsync(new MemoryStream(jpegBytes), "Hello.jpeg"); }
//private static string unformattedHtml = File.ReadAllText(directory + file); public static byte[] HtmlToJpeg(UserAccount user) { string userName = user.username; string userXp = "XP: " + user.XP.ToString(); string userLvl = "Level: " + user.lvl.ToString(); HtmlBuilder.BuildNewDoc(userName, userXp, userLvl); var convert = new HtmlToImageConverter { Width = 200, Height = 150 }; var bytes = convert.GenerateImageFromFile(file, ImageFormat.Jpeg); return(bytes); }
public async Task GeneratedImage(string color = "red", SocketUser user = null) { if (user == null) { user = Context.User as SocketGuildUser; } string css = "<style>\n h1{\n color: " + color + ";\n }\n</style>\n"; string html = String.Format("<h1>Who's Thicc? {0}!<h1>", user.Username); var converter = new HtmlToImageConverter { Width = 340, Height = 110 }; var jpgBytes = converter.GenerateImage(css + html, NReco.ImageGenerator.ImageFormat.Jpeg); await Context.Channel.SendFileAsync(new MemoryStream(jpgBytes), "hello.jpg"); }
public async Task Test() { try { var userImg = @"https://cdn.discordapp.com/avatars/" + Context.User.Id + @"/" + Context.User.AvatarId + @".png".Replace(" ", "%20"); string html = String.Format($"<html><head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.0/css/bootstrap.min.css\"></head><body style=\"overflow:hidden;background-image:url("http://zanoxhosting.ga/DMNHosting/api/discord/welcomeAssets/img/eS4IxK3.png");\"> <div style=\"display:table;position:absolute;top:0;left:0;height:100%;width:100%;\"> <div style=\"display:table-cell;vertical-align:middle;\"> <div style=\"margin-left:auto;margin-right:auto;text-align:center;\"><img src=\"{userImg}\" style=\"height:125px;width:125px;\"><div></div>\" <div style=\"color:#FFF;\"><h1 style=\"font-size:25px;\"><b>Welcome to {Context.Guild.Name},</b></h1> <h1 style=\"font-size:15px;\"><b>{Context.User.Username}</b></h1> </div></div></div></div><script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.0/js/bootstrap.bundle.min.js\"></script></body></html>"); var converter = new HtmlToImageConverter { Width = 500, Height = 250 }; var jpgBytes = converter.GenerateImage(html, NReco.ImageGenerator.ImageFormat.Png); await Context.Guild.DefaultChannel.SendMessageAsync("test"); await Context.Channel.SendFileAsync(new MemoryStream(jpgBytes), $"Welcome {Context.User.Username}.png"); } catch (Exception e) { ExceptionAlert(Context, e); } }
public async Task AnnounceLeave(SocketGuildUser user) //Welcomes the new user { var account = UserAccounts.GetOrCreateAccount(user.Guild.Id); var channel = _client.GetChannel(account.DefaultChannelID) as SocketTextChannel; // Gets the channel to send the message in var userImg = @"https://cdn.discordapp.com/avatars/" + user.Id + @"/" + user.AvatarId + @".png".Replace(" ", "%20"); string html = String.Format($"<html><head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.0/css/bootstrap.min.css\"></head><body style=\"overflow:hidden;background-image:url("http://zanoxhosting.ga/api/discord/welcomeAssets/img/eS4IxK3.png");\"> <div style=\"display:table;position:absolute;top:0;left:0;height:100%;width:100%;\"> <div style=\"display:table-cell;vertical-align:middle;\"> <div style=\"margin-left:auto;margin-right:auto;text-align:center;\"><img src=\"{userImg}\" style=\"height:125px;width:125px;\"><div></div>\" <div style=\"color:#FFF;\"><h1 style=\"font-size:25px;\"><b>Farewell,</b></h1> <h1 style=\"font-size:15px;\"><b>{user.Username}</b></h1> </div></div></div></div><script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.0/js/bootstrap.bundle.min.js\"></script></body></html>"); var converter = new HtmlToImageConverter { Width = 500, Height = 250 }; byte[] jpgBytes = converter.GenerateImage(html, NReco.ImageGenerator.ImageFormat.Png); File.WriteAllBytes($"Farewell {user.Username}.png", jpgBytes); await channel.SendFileAsync($"Farewell {user.Username}.png", $"Farewell, {user.Mention}"); try { File.Delete($"Farewell {user.Username}.png"); } catch { } }
public async Task RenderHTML(CommandContext Context, params string[] url) { using (HttpClient client = new HttpClient()) { using (HttpResponseMessage response = await client.GetAsync(string.Join(" ", url))) { using (HttpContent content = response.Content) { string myContent = await content.ReadAsStringAsync(); string html = string.Format("{0}", myContent); var converter = new HtmlToImageConverter { Width = 1920, Height = 1080 }; var pngBytes = converter.GenerateImage(html, NReco.ImageGenerator.ImageFormat.Png); await Context.Channel.SendFileAsync(new MemoryStream(pngBytes), "gya.png"); } } } }
public static string ToPng(string json, string fileName) { string outFile = fileName.Substring(0, fileName.LastIndexOf(".", StringComparison.CurrentCultureIgnoreCase)) + ".jpg"; string dir = System.Environment.CurrentDirectory; string h1 = File.ReadAllText(dir + "\\HTML\\head.html"); string h2 = File.ReadAllText(dir + "\\HTML\\foot.html"); var imageCons = new HtmlToImageConverter(); imageCons.Width = 1200; var bytes = imageCons.GenerateImage(h1 + json + h2, ImageFormat.Jpeg); using (StreamWriter sw = new System.IO.StreamWriter(outFile)) { sw.BaseStream.Write(bytes, 0, bytes.Length - 1); sw.Close(); } return(outFile); }
public static byte[] GenerateImage(string html, string format = "png", int?width = null, int?height = null) { var htmlToImageConv = new HtmlToImageConverter(); if (format == "png") { htmlToImageConv.CustomArgs = "--transparent"; } if (width.HasValue) { htmlToImageConv.Width = width.Value; } if (height.HasValue) { htmlToImageConv.Height = height.Value; } var image = htmlToImageConv.GenerateImage(html, format == "jpg" ? ImageFormat.Jpeg : ImageFormat.Png); return(image); }
public ActionResult ConvertHtmlToImage(IFormCollection collection) { // Create a HTML to Image converter object with default settings HtmlToImageConverter htmlToImageConverter = new HtmlToImageConverter(); // Set license key received after purchase to use the converter in licensed mode // Leave it not set to use the converter in demo mode htmlToImageConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c="; // Set HTML Viewer width in pixels which is the equivalent in converter of the browser window width htmlToImageConverter.HtmlViewerWidth = int.Parse(collection["htmlViewerWidthTextBox"]); // Set HTML viewer height in pixels to convert the top part of a HTML page // Leave it not set to convert the entire HTML if (collection["htmlViewerHeightTextBox"][0].Length > 0) { htmlToImageConverter.HtmlViewerHeight = int.Parse(collection["htmlViewerHeightTextBox"]); } // Set if the created image has a transparent background htmlToImageConverter.TransparentBackground = SelectedImageFormat(collection["imageFormatComboBox"]) == System.Drawing.Imaging.ImageFormat.Png ? collection["transparentBackgroundCheckBox"].Count > 0 : false; // Set the maximum time in seconds to wait for HTML page to be loaded // Leave it not set for a default 60 seconds maximum wait time htmlToImageConverter.NavigationTimeout = int.Parse(collection["navigationTimeoutTextBox"]); // Set an adddional delay in seconds to wait for JavaScript or AJAX calls after page load completed // Set this property to 0 if you don't need to wait for such asynchcronous operations to finish if (collection["conversionDelayTextBox"][0].Length > 0) { htmlToImageConverter.ConversionDelay = int.Parse(collection["conversionDelayTextBox"]); } System.Drawing.Image[] imageTiles = null; if (collection["HtmlPageSource"] == "convertUrlRadioButton") { string url = collection["urlTextBox"]; // Convert the HTML page given by an URL to a set of Image objects imageTiles = htmlToImageConverter.ConvertUrlToImageTiles(url); } else { string htmlString = collection["htmlStringTextBox"]; string baseUrl = collection["baseUrlTextBox"]; // Convert a HTML string with a base URL to a set of Image objects imageTiles = htmlToImageConverter.ConvertHtmlToImageTiles(htmlString, baseUrl); } // Save the first image tile to a memory buffer System.Drawing.Image outImage = imageTiles[0]; // Create a memory stream where to save the image System.IO.MemoryStream imageOutputStream = new System.IO.MemoryStream(); // Save the image to memory stream outImage.Save(imageOutputStream, SelectedImageFormat(collection["imageFormatComboBox"])); // Write the memory stream to a memory buffer imageOutputStream.Position = 0; byte[] outImageBuffer = imageOutputStream.ToArray(); // Close the output memory stream imageOutputStream.Close(); string imageFormatName = collection["imageFormatComboBox"][0].ToLower(); // Send the image file to browser FileResult fileResult = new FileContentResult(outImageBuffer, "image/" + (imageFormatName == "jpg" ? "jpeg" : imageFormatName)); fileResult.FileDownloadName = "HTML_to_Image." + imageFormatName; return(fileResult); }
public ActionResult Print(int id) { var secretNumber = Guid.NewGuid().ToString(); ArtifactCloneController.SecretNumber = secretNumber; var displayUrl = Url.Action("Display", "ArtifactClone", new { id = id, secretNumber = secretNumber },this.Request.Url.Scheme); var htmlToImageConverter = new HtmlToImageConverter(); htmlToImageConverter.Height = 350; htmlToImageConverter.Width = 500; return File(htmlToImageConverter.GenerateImageFromFile(displayUrl, ImageFormat.Png), "image/png","TheGraph.png"); }
/// <summary> /// Send the PDF document referenced by "dt" to the PACS system defined in the database lkpInterfaceDefinitions for this document /// effective 1/22/16 the values required to be present in lkpInterfaceDefinitions are as follows: /// interfaceType = "PACS" /// ipAddress, port self explanatory /// stringParam1: "their" AET /// stringParam2: "our" AET /// stringParam3: qualified path to DCMTK binaries, e.g., C:\HUGHES_DCMTK_DICOM\bin /// intParam1: send file type, see enum. 1=pdf, 2=jpg, 3=bmp /// stringParam4: Modality to send to PACS. Defaults to "OT" /// stringParam5: Additional parameters. see documentation for DCMTK "storescu". e.g., when sending a jpg, you might have to specify jpg type, e.g., "-xy" /// </summary> /// <param name="dt">Document Template, as per the HTML document generation</param> /// <param name="patient">V3 Patient object</param> /// <param name="filename">Name of the PDF file to be converted to a .DCM (DICOM) file and transmitted to PACS</param> /// <param name="apptId">Appointment ID</param> /// <returns></returns> public static bool send2PACS(DocumentTemplate dt, RiskApps3.Model.PatientRecord.Patient patient, string filenameIn, int apptId) { List<TripleArg> args = new List<TripleArg>(); // for want of a tuple which doesn't exist till .NET 4.0 List<KeyValuePair<string, string>> dicomOutputArgs = new List<KeyValuePair<string, string>>(); List<InterfaceInstance> interfaces = new List<InterfaceInstance>(); string accessionNumber = ""; string patientname = ""; string dob = ""; string gender = ""; string apptDate = ""; string apptTime = ""; ParameterCollection pacsArgs = new ParameterCollection(); pacsArgs.Add("documentTemplateID", dt.documentTemplateID); string filename; Image img = null; SqlDataReader reader = BCDB2.Instance.ExecuteReaderSPWithParams("sp_getInterfaceDefinitionFromTemplateID", pacsArgs); while (reader.Read()) { InterfaceInstance instance = new InterfaceInstance(); if (reader.IsDBNull(0) == false) { instance.InterfaceId = reader.GetInt32(0); } if (reader.IsDBNull(1) == false) { instance.InterfaceType = reader.GetString(1); } if (reader.IsDBNull(2) == false) { instance.IpAddress = reader.GetString(2); } if (reader.IsDBNull(3) == false) { instance.Port = reader.GetString(3); } if (reader.IsDBNull(4) == false) { instance.AeTitleRemote = reader.GetString(4); } if (reader.IsDBNull(5) == false) { instance.AeTitleLocal = reader.GetString(5); } if (reader.IsDBNull(6) == false) { instance.DCMTKpath = reader.GetString(6); } if (reader.IsDBNull(7) == false) { instance.PacsSubType = reader.GetInt32(7); // for now, 1 == PDF, 2 == JPG, 3 == BMP (see enum pacsSubTypes, above) } // there is no intParam2 for PACS as yet...skipping ahead to the new-as-of-jan-2016 string param 4 if (reader.IsDBNull(9) == false) { instance.Modality = reader.GetString(9); } if (reader.IsDBNull(10) == false) { instance.AdditionalParams = reader.GetString(10); } if (instance.InterfaceId > 0) { interfaces.Add(instance); // multiple PACS interfaces per document are now supported. } } // just do this once... if (apptId > 0) { // This is an FMH specific hack, they are sending the Accession Number in the HL7 ADT_A08 message in PID|26... // and it is being stored in the appointment table in the unused field "referral". // No more obvious way of accomplishing this has jumped out at me yet, but this will have to be made more generic as new // customers are brought on-line. string sqlStr = "SELECT referral,patientname,dob,gender,apptDate,apptTime FROM tblAppointments WHERE apptID=" + apptId.ToString() + ";"; reader = BCDB2.Instance.ExecuteReader(sqlStr); while (reader.Read()) { if (reader.IsDBNull(0) == false) { accessionNumber = reader.GetString(0); } if (reader.IsDBNull(1) == false) // taking this from appointment table, alternatively, could use Patient object { patientname = reader.GetString(1); } if (reader.IsDBNull(2) == false) { dob = reader.GetString(2); } if (reader.IsDBNull(3) == false) { gender = reader.GetString(3); } if (reader.IsDBNull(4) == false) { apptDate = reader.GetString(4); } if (reader.IsDBNull(5) == false) { apptTime = reader.GetString(5); } } reader.Close(); } foreach (InterfaceInstance iface in interfaces) // send document to each eligible interface, converting it as need be { if ((iface.InterfaceId > 0) && (iface.InterfaceType == "PACS")) // no interface? not a PACS interface? bye bye! { // Ok! We're sending this thing to PACS... go ahead and convert the PDF file to a DCM file... // This will call into the DCMTK library to do their pdf2dcm, dcmodify (to set metadata), and storescu. Add appropriate parameters to the DCM. filename = filenameIn; // reinit // filter out oddball cases of calling this method with conflicting interface parameters versus the type of file passed in. // however, we WILL reconvert PDFs to an image upon demand, see below. if (((filename.ToUpper().Contains(".JPG")) || (filename.ToUpper().Contains(".BMP"))) && (iface.PacsSubType == (int)pacsSubTypes.PDF)) { Logger.Instance.WriteToLog("Send2PACS: Attempted to send an image file to a PDF interface, interfaceID #" + iface.InterfaceId + ". Request Aborted" + (apptId > 0 ? " for appt id " + apptId.ToString() + "." : ".")); continue; } if (iface.PacsSubType == (int)pacsSubTypes.JPG) // jpg { // If we were sent a PDF file, yet it's pacsSubType is different, convert the document to an image // this could happen depending on what type of file is generated from the survey, and the settings made in lkpInterfaceDefinitions // as of now, we're not converting between jpgs and bmps... if you send a bmp and interface type is jpg, bail... and vice versa if (filename.ToUpper().Contains(".BMP")) { Logger.Instance.WriteToLog("Send2PACS: Attempted to send a BMP file to a JPG interface. Request Aborted" + (apptId > 0 ? " for appt id " + apptId.ToString() + "." : ".")); continue; } if (filename.ToUpper().Contains(".PDF")) // re-convert this html to an image instead { HtmlToImageConverter htmlToJpgConverter = new HtmlToImageConverter(); htmlToJpgConverter.LicenseKey = "sjwvPS4uPSskPSgzLT0uLDMsLzMkJCQk"; filename = filename.ToUpper().Replace(".PDF", "") + ".jpg"; htmlToJpgConverter.ConvertHtmlToFile(dt.htmlText, "", System.Drawing.Imaging.ImageFormat.Jpeg, filename); } } if ((iface.PacsSubType == (int)pacsSubTypes.BMP) || (iface.PacsSubType == (int)pacsSubTypes.inverseBMP)) // bitmap { // If we were sent a PDF file, yet it's pacsSubType is different, convert the document to an image // this could happen depending on what type of file is generated from the survey, and the settings made in lkpInterfaceDefinitions // as of now, we're not converting between jpgs and bmps... if you send a bmp and interface type is jpg, bail... and vice versa if (filename.ToUpper().Contains(".JPG")) { Logger.Instance.WriteToLog("Send2PACS: Attempted to send a JPG file to a BMP interface. Request Aborted" + (apptId > 0 ? " for appt id " + apptId.ToString() + "." : ".")); continue; } if (filename.ToUpper().Contains(".PDF")) // re-convert this html to an image instead { HtmlToImageConverter htmlToJpgConverter = new HtmlToImageConverter(); htmlToJpgConverter.LicenseKey = "sjwvPS4uPSskPSgzLT0uLDMsLzMkJCQk"; filename = filename.ToUpper().Replace(".PDF", "") + ".bmp"; if (iface.PacsSubType == (int)pacsSubTypes.inverseBMP) { img = htmlToJpgConverter.ConvertHtmlToImageObject(dt.htmlText, ""); } else { htmlToJpgConverter.ConvertHtmlToFile(dt.htmlText, "", System.Drawing.Imaging.ImageFormat.Bmp, filename); } } // jdg 1/26/2016 invert bmp if (iface.PacsSubType == (int)pacsSubTypes.inverseBMP) { InvertBitmap(filename, img); } } args.Clear(); string dcmFilename = filename + ".dcm"; TripleArg arg1 = new TripleArg(); //arg1.ArgSwitch = filename; arg1.ArgSwitch = "\"" + filename + "\""; args.Add(arg1); TripleArg arg2 = new TripleArg(); //arg2.ArgSwitch = dcmFilename; arg2.ArgSwitch = "\"" + dcmFilename + "\""; args.Add(arg2); if ((patient != null) && (iface.PacsSubType == (int)pacsSubTypes.PDF)) // for some reason, img2dcm (jpg) doesn't have a patient identifier arg. will have to insert this into the metadata later. { TripleArg arg3 = new TripleArg(); arg3.ArgSwitch = "+pi"; arg3.Name = patient.unitnum; args.Add(arg3); } if ((iface.PacsSubType == (int)pacsSubTypes.BMP) || (iface.PacsSubType == (int)pacsSubTypes.inverseBMP)) // defaults to jpg { TripleArg arg4 = new TripleArg(); arg4.ArgSwitch = "-i"; arg4.Name = "BMP"; args.Add(arg4); } if ((iface.PacsSubType == (int)pacsSubTypes.JPG) || (iface.PacsSubType == (int)pacsSubTypes.BMP) || (iface.PacsSubType == (int)pacsSubTypes.inverseBMP)) // jpg, bmp { // do the conversion jpg --> dcm; this is a local command, no ip/port needed for this one. wrapDCMTKmethodAsExternalCommand(null, null, iface.DCMTKpath + "\\img2dcm.exe", args); } else { // do the conversion pdf --> dcm; this is a local command, no ip/port needed for this one. wrapDCMTKmethodAsExternalCommand(null, null, iface.DCMTKpath + "\\pdf2dcm.exe", args); } if (!File.Exists(dcmFilename)) { Logger.Instance.WriteToLog("Send2PACS: Unable to convert JPG or PDF to DCM OR perhaps just unable to write it to disk. Check lkp_AutomationDocuments, lkpInterfaceDefinitions, document storage location and DICOM binary library (" + iface.DCMTKpath + ") for existence and/or permissions. Filename: " + dcmFilename + "."); continue; // something went wrong, but didn't throw an error... } // I'm guessing that we'll be adding a study/series ID later, just add another TripleArg here, if you didn't build the DCM with it in the metadata initially // If you need to fetch the UID, here is a sample of what a findscu would look like... don't forget the -aec and -aet... // findscu localhost 5678 -S -k StudyInstanceUID -k QueryRetrieveLevel=STUDY -k AccessionNumber=22222893 -aet Hughes -aec Hughes2 // and of course, you have to read the resulting array list. args.Clear(); TripleArg modArg0 = new TripleArg(); // dcm file name modArg0.ArgSwitch = "\"" + dcmFilename + "\""; args.Add(modArg0); if (!String.IsNullOrEmpty(accessionNumber)) { TripleArg modArg1 = new TripleArg(); // accession number modArg1.ArgSwitch = "-m"; modArg1.Name = "AccessionNumber"; // DICOM literal string, do not modify modArg1.Value = accessionNumber; args.Add(modArg1); } else { // make a note of this circumstance, it's especially critical for FMH Logger.Instance.WriteToLog("Send2PACS: Accession number is not set for Interface #" + iface.InterfaceId + " for appt # : " + apptId.ToString()); } TripleArg modArg2 = new TripleArg(); // Modality hard-coded to "OT". May need to be parameterized later. modArg2.ArgSwitch = "-i"; modArg2.Name = "Modality"; // DICOM literal string, do not modify modArg2.Value = iface.Modality; // "OT"; no longer hard-coded jdg 1/21/16 args.Add(modArg2); TripleArg modArg3 = new TripleArg(); // Patient Name modArg3.ArgSwitch = "-m"; modArg3.Name = "PatientName"; // DICOM literal string, do not modify patientname = patientname.Replace(", ", ","); // hack for extra space in name... patientname = patientname.Replace(", ", ","); // hack for extra space in name... modArg3.Value = "\"" + patientname.Replace(",", "^") + "\""; args.Add(modArg3); try { if (!String.IsNullOrEmpty(dob)) { dob = DateTime.ParseExact(dob, "MM/dd/yyyy", CultureInfo.InvariantCulture).ToString("yyyyMMdd"); // FMH preferred format... DICOM Standard?? } } catch (Exception) { } // else use dob as found in database TripleArg modArg4 = new TripleArg(); // Date of Birth modArg4.ArgSwitch = "-m"; modArg4.Name = "PatientBirthDate"; // DICOM literal string, do not modify modArg4.Value = dob; args.Add(modArg4); TripleArg modArg5 = new TripleArg(); // Gender modArg5.ArgSwitch = "-m"; modArg5.Name = "PatientSex"; // DICOM literal string, do not modify modArg5.Value = gender; args.Add(modArg5); try { if (!String.IsNullOrEmpty(apptDate)) { apptDate = DateTime.ParseExact(apptDate, "MM/dd/yyyy", CultureInfo.InvariantCulture).ToString("yyyyMMdd"); } } catch (Exception) { } // else use apptDate as found in database TripleArg modArg6 = new TripleArg(); // Study Date modArg6.ArgSwitch = "-m"; modArg6.Name = "StudyDate"; // DICOM literal string, do not modify modArg6.Value = apptDate; args.Add(modArg6); if ((iface.PacsSubType == (int)pacsSubTypes.JPG) || (iface.PacsSubType == (int)pacsSubTypes.BMP)) // pdf already has this in the metadata; img2dcm won't take patient id argument like pdf2dcm, for reasons that escape me { TripleArg modArg7 = new TripleArg(); // MRN modArg7.ArgSwitch = "-m"; modArg7.Name = "PatientID"; // DICOM literal string, do not modify modArg7.Value = patient.unitnum; args.Add(modArg7); } try { if (!String.IsNullOrEmpty(apptTime)) { apptTime = DateTime.ParseExact(apptTime, "hh:mm tt", CultureInfo.InvariantCulture).ToString("hhmm") + "00"; TripleArg modArg8 = new TripleArg(); // Date of Birth modArg8.ArgSwitch = "-m"; modArg8.Name = "StudyTime"; // DICOM literal string, do not modify modArg8.Value = apptTime; args.Add(modArg8); } } catch (Exception) { } // no time? no big deal. TripleArg modArg9 = new TripleArg(); // Study ID modArg9.ArgSwitch = "-m"; modArg9.Name = "StudyID"; // DICOM literal string, do not modify //modArg9.Value = "1"; modArg9.Value = iface.InterfaceId.ToString(); args.Add(modArg9); TripleArg modArg10 = new TripleArg(); // Series ID modArg10.ArgSwitch = "-m"; modArg10.Name = "SeriesNumber"; // DICOM literal string, do not modify //modArg10.Value = "1"; modArg10.Value = iface.InterfaceId.ToString(); args.Add(modArg10); TripleArg modArg11 = new TripleArg(); // Instance modArg11.ArgSwitch = "-m"; modArg11.Name = "InstanceNumber"; // DICOM literal string, do not modify //modArg11.Value = "1"; modArg11.Value = iface.InterfaceId.ToString(); args.Add(modArg11); wrapDCMTKmethodAsExternalCommand(null, null, iface.DCMTKpath + "\\dcmodify.exe", args); args.Clear(); TripleArg sendArg1 = new TripleArg(); // file to xmit sendArg1.ArgSwitch = "\"" + dcmFilename + "\""; args.Add(sendArg1); TripleArg sendArg2 = new TripleArg(); // ae title HRA sendArg2.ArgSwitch = "-aet"; sendArg2.Name = iface.AeTitleLocal; args.Add(sendArg2); TripleArg sendArg3 = new TripleArg(); // ae title remote sendArg3.ArgSwitch = "-aec"; sendArg3.Name = iface.AeTitleRemote; args.Add(sendArg3); if (!String.IsNullOrEmpty(iface.AdditionalParams)) { TripleArg sendArg4 = new TripleArg(); // additional params sendArg4.ArgSwitch = iface.AdditionalParams; args.Add(sendArg4); } // Send it out... finally! dicomOutputArgs = wrapDCMTKmethodAsExternalCommand(iface.IpAddress, iface.Port, iface.DCMTKpath + "\\storescu.exe", args); // todo: parse out any useful returned values... in the meantime, unless an error is thrown we'll return success Logger.Instance.WriteToLog("Send2PACS: Successful send to " + iface.AeTitleRemote + " for Interface #" + iface.InterfaceId + " " + (apptId > 0 ? " for appt id " + apptId.ToString() : "")); try { File.Delete(dcmFilename); // no point in keeping these around. File.Delete(dcmFilename + ".bak"); File.Delete(filename); } catch (Exception e) { Logger.Instance.WriteToLog("Send2PACS: Unable to delete " + dcmFilename + ", underlying error was " + e.Message); } } } // if some interfaces were processed, return true. if (interfaces.Count > 0) return true; else return false; }
private Bitmap ConvertHtmlToImage(string html) { byte[] pngBytes = new HtmlToImageConverter().GenerateImage(html, ImageFormat.Png); Bitmap bmp; using (var ms = new MemoryStream(pngBytes)) bmp = new Bitmap(ms); return bmp; }
public void SetUp() { processServiceMock = new Mock <IProcessService>(); htmlToImageConverter = new HtmlToImageConverter(processServiceMock.Object); }
public async Task <string> MakeCertificate(string UserName, string language) { string result = null; language = "ru"; try { UserInfo userinfo = await db.UserInfoes.FirstOrDefaultAsync(e => e.UserName == UserName); string Lname = ""; string Fname = ""; if (userinfo.Lname != null) { Lname = userinfo.Lname; } if (userinfo.Fname != null) { Fname = userinfo.Fname; } DateTime CurrentDate = DateTime.Now.AddHours(6); string Day = CurrentDate.Day.ToString(); string Month = CurrentDate.Month.ToString(); string Year = CurrentDate.Year.ToString(); string Date = Day + "." + Month + "." + Year; string imageName = ""; await System.Threading.Tasks.Task.Run(() => { int usernameLg = (Lname.Length + Fname.Length) / 2; int fontSize = 140; int alfa = 840 - usernameLg * 89; if (usernameLg > 20) { fontSize = 120; alfa = 840 - usernameLg * 80; } int leftPosition = 600 + alfa; var htmlToImageConv = new HtmlToImageConverter(); //string html = "<html> <head><meta http-equiv=Content-Type content='text/html; charset=UTF-8'><style type='text/css'>@font-face{font-family: 'Font Name';src: url('http://academy.marinehealth.asia/Images/cert/10846.ttf') format('truetype');}body {font-family: 'Font Name', Fallback, sans-serif;}</style><script type = 'text/javascript' src = 'a8535914-f191-11e9-9d71-0cc47a792c0a_id_a8535914-f191-11e9-9d71-0cc47a792c0a_files/wz_jsgraphics.js' ></script></head><body ><div style = 'position:absolute;left:50%;margin-left:-1462px;top:0px;width:2924px;height:1995px;border-style:outset;overflow:hidden' > <div style = 'position:absolute;left:0px;top:0px' ><img src='http://academy.marinehealth.asia/Images/cert/cert-ru.jpg'></div><div style = 'position:absolute;right:120px;top:820px;color:#2b529f;font-size:" + fontsize + ";text-align:end'>" + Lname + " <br>" + Fname + " </div><div style='position: absolute; right: 150px; top: 1875px;color:#2b529f;font-size:50px;'>" + DateTime.Now.AddHours(6).ToString("dd.MM.yyyy") + "</div></body></html>"; string html = "<html> <head><meta http-equiv=Content-Type content='text/html; charset=UTF-8'><style type='text/css'></style><script type = 'text/javascript' src = 'a8535914-f191-11e9-9d71-0cc47a792c0a_id_a8535914-f191-11e9-9d71-0cc47a792c0a_files/wz_jsgraphics.js'></script></head><body style='font-family: Geneva, Arial, Helvetica, sans-serif'><div style = 'position:absolute;left:50%;margin-left:-1462px;top:0px;width:2924px;height:2075px;border-style:outset;overflow:hidden'> <div style = 'position:absolute;left:0px;top:0px' ><img src='http://academy.marinehealth.asia/Images/cert/certificate-v3.jpg'></div><div style='position:absolute;left:" + leftPosition + "px;top:1030px;color:#000;font-size:" + fontSize + "px;font-weight:900'>" + Lname + " " + Fname + "</div><div style='position: absolute; left:1350px;top:1770px;color:#717171;font-size:45px;font-weight:900'>" + DateTime.Now.AddHours(6).ToString("dd.MM.yyyy") + "</div></body></html>"; //string html = "<html><head><meta http-equiv=Content-Type content='text/html; charset=UTF-8'><meta name='viewport' content='width = device - width, minimum - scale = 0.1' ></head><body style='margin: 0px; background: #0e0e0e;font-family: Geneva, Arial, Helvetica, sans-serif;'><img style='-webkit-user-select: none;margin: auto;display:table' src='http://academy.marinehealth.asia/Images/cert/certificate-v3.jpg' width='1320' height='930'><div style='position:absolute;left:" + leftPosition + "px;top:480px;color:#000000;font-size:" + fontSize + "px'>Шарипжанов Айдар</div><div style='position:absolute; left:1020px; top:795px; color:#615f60d9; font-size:17px; font-weight:900'>04.11.2020</div></body></html>"; var img = htmlToImageConv.GenerateImage(html, ImageFormat.Jpeg); imageName = "~/Images/UserCertificate/" + userinfo.Fname + "_" + "(certificate_" + userinfo.Id + ")" + ".jpg"; string path = HttpContext.Current.Server.MapPath(imageName); System.IO.File.WriteAllBytes(path, img); }); Users_Certificates UserCerNew = new Users_Certificates(); UserCerNew.CertificateURL = imageName; UserCerNew.PublicCert = true; UserCerNew.UserId = userinfo.Id; UserCerNew.TypeCert = 3; UserCerNew.MakeDate = DateTime.Now.AddHours(6).Date; db.Users_Certificates.Add(UserCerNew); await db.SaveChangesAsync(); result = imageName; } catch { } return(result); }
protected void convertToImageButton_Click(object sender, EventArgs e) { // Create a HTML to Image converter object with default settings HtmlToImageConverter htmlToImageConverter = new HtmlToImageConverter(); // Set license key received after purchase to use the converter in licensed mode // Leave it not set to use the converter in demo mode htmlToImageConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c="; // Set HTML Viewer width in pixels which is the equivalent in converter of the browser window width htmlToImageConverter.HtmlViewerWidth = int.Parse(htmlViewerWidthTextBox.Text); // Set HTML viewer height in pixels to convert the top part of a HTML page // Leave it not set to convert the entire HTML if (htmlViewerHeightTextBox.Text.Length > 0) { htmlToImageConverter.HtmlViewerHeight = int.Parse(htmlViewerHeightTextBox.Text); } // Set if the created image has a transparent background htmlToImageConverter.TransparentBackground = SelectedImageFormat() == System.Drawing.Imaging.ImageFormat.Png ? transparentBackgroundCheckBox.Checked : false; // Set the maximum time in seconds to wait for HTML page to be loaded // Leave it not set for a default 60 seconds maximum wait time htmlToImageConverter.NavigationTimeout = int.Parse(navigationTimeoutTextBox.Text); // Set an adddional delay in seconds to wait for JavaScript or AJAX calls after page load completed // Set this property to 0 if you don't need to wait for such asynchcronous operations to finish if (conversionDelayTextBox.Text.Length > 0) { htmlToImageConverter.ConversionDelay = int.Parse(conversionDelayTextBox.Text); } System.Drawing.Image[] imageTiles = null; if (convertUrlRadioButton.Checked) { string url = urlTextBox.Text; // Convert the HTML page given by an URL to a set of Image objects imageTiles = htmlToImageConverter.ConvertUrlToImageTiles(url); } else { string htmlString = htmlStringTextBox.Text; string baseUrl = baseUrlTextBox.Text; // Convert a HTML string with a base URL to a set of Image objects imageTiles = htmlToImageConverter.ConvertHtmlToImageTiles(htmlString, baseUrl); } // Save the first image tile to a memory buffer System.Drawing.Image outImage = imageTiles[0]; // Create a memory stream where to save the image System.IO.MemoryStream imageOutputStream = new System.IO.MemoryStream(); // Save the image to memory stream outImage.Save(imageOutputStream, SelectedImageFormat()); // Write the memory stream to a memory buffer imageOutputStream.Position = 0; byte[] outImageBuffer = imageOutputStream.ToArray(); // Close the output memory stream imageOutputStream.Close(); // Send the image as response to browser string imageFormatName = imageFormatComboBox.SelectedValue.ToLower(); // Set response content type Response.AddHeader("Content-Type", "image/" + (imageFormatName == "jpg" ? "jpeg" : imageFormatName)); // Instruct the browser to open the image file as an attachment or inline Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}; size={1}", "HTML_to_Image." + imageFormatName, outImageBuffer.Length.ToString())); // Write the image buffer to HTTP response Response.BinaryWrite(outImageBuffer); // End the HTTP response and stop the current page processing Response.End(); }