using iText.Samples.Util; using System; using System.IO; using System.Net; using iText.Commons.Utils; using iText.Html2pdf; using iText.Kernel.Geom; using iText.Kernel.Pdf; using iText.Licensing.Base; using iText.StyledXmlParser.Css.Media; namespace iText.Samples.Htmlsamples.Chapter07 { /// /// Converts a simple HTML file to PDF using an InputStream and an OutputStream /// as arguments for the convertToPdf() method. /// public class C07E05_CreateFromURL2 { const string USER_AGENT = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; WOW64; " + "Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; " + ".NET CLR 3.5.21022; .NET CLR 3.5.30729; .NET CLR 3.0.30618; " + "InfoPath.2; OfficeLiveConnector.1.3; OfficeLivePatch.0.0)"; /// /// The path to the resulting PDF file. /// public static readonly String DEST = "results/htmlsamples/ch07/url2pdf_2.pdf"; /// /// The target folder for the result. /// public static readonly String ADDRESS = "https://stackoverflow.com/help/on-topic"; /// /// The main method of this example. /// /// no arguments are needed to run this example. public static void Main(String[] args) { String licensePath = LicenseUtil.GetPathToLicenseFileWithITextCoreAndPdfHtmlAndPdfCalligraphProducts(); using (Stream license = FileUtil.GetInputStreamForFile(licensePath)) { LicenseKey.LoadLicenseFile(license); } FileInfo file = new FileInfo(DEST); file.Directory.Create(); new C07E05_CreateFromURL2().CreatePdf(new Uri(ADDRESS), DEST); } /// /// Creates the PDF file. /// /// the URL object for the web page /// the path to the resulting PDF public void CreatePdf(Uri url, String dest) { PdfWriter writer = new PdfWriter(dest); PdfDocument pdf = new PdfDocument(writer); PageSize pageSize = new PageSize(850, 1700); pdf.SetDefaultPageSize(pageSize); ConverterProperties properties = new ConverterProperties(); MediaDeviceDescription mediaDeviceDescription = new MediaDeviceDescription(MediaType.SCREEN); mediaDeviceDescription.SetWidth(pageSize.GetWidth()); properties.SetMediaDeviceDescription(mediaDeviceDescription); var webClient = new TimedWebClient(); // Some websites forbid web-page access if user-agent is not defined. webClient.Headers.Add("User-Agent", USER_AGENT); try { byte[] website = webClient.DownloadData(url); HtmlConverter.ConvertToPdf(new MemoryStream(website), pdf, properties); } catch (WebException e) { if (e.Status == WebExceptionStatus.Timeout) { // Handle timout } else { // Handle http status code int responseCode = (int)((HttpWebResponse)e.Response).StatusCode; } } } internal class TimedWebClient : WebClient { protected override WebRequest GetWebRequest(Uri address) { var webRequest = base.GetWebRequest(address); webRequest.Timeout = 15000; return webRequest; } } } }