Skip to content

Instantly share code, notes, and snippets.

@NikolayIT
Last active March 28, 2023 08:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save NikolayIT/5a2b110905f25a091dd620412e1fb665 to your computer and use it in GitHub Desktop.
Save NikolayIT/5a2b110905f25a091dd620412e1fb665 to your computer and use it in GitHub Desktop.
using System;
using System.Diagnostics;
using System.IO;
public interface IHtmlToPdfConverter
{
byte[] Convert(string basePath, string htmlCode, FormatType formatType, OrientationType orientationType);
}
public class HtmlToPdfConverter : IHtmlToPdfConverter
{
public byte[] Convert(string basePath, string htmlCode, FormatType formatType = FormatType.A4, OrientationType orientationType = OrientationType.Portrait)
{
var inputFileName = $"input_{Guid.NewGuid()}.html";
var outputFileName = $"output_{Guid.NewGuid()}.pdf";
File.WriteAllText($"{basePath}/{inputFileName}", htmlCode);
var startInfo = new ProcessStartInfo("phantomjs.exe")
{
WorkingDirectory = basePath,
Arguments = $"rasterize.js \"{inputFileName}\" \"{outputFileName}\" \"{formatType}\" \"{orientationType.ToString().ToLower()}\"",
UseShellExecute = true,
};
var process = new Process { StartInfo = startInfo };
process.Start();
process.WaitForExit();
var bytes = File.ReadAllBytes($"{basePath}/{outputFileName}");
File.Delete($"{basePath}/{inputFileName}");
File.Delete($"{basePath}/{outputFileName}");
return bytes;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment