Example #1
0
        /// <summary>
        ///     Converts the given <paramref name="inputUri" /> to PDF
        /// </summary>
        /// <param name="inputUri">The webpage to convert</param>
        /// <param name="outputFile">The output file</param>
        /// <param name="pageSettings"><see cref="PageSettings"/></param>
        /// <param name="waitForWindowStatus">Wait until the javascript window.status has this value before
        ///     rendering the PDF</param>
        /// <param name="waitForWindowsStatusTimeout"></param>
        /// <param name="conversionTimeout">An conversion timeout in milliseconds, if the conversion failes
        /// to finished in the set amount of time then an <see cref="ConversionTimedOutException"/> is raised</param>
        /// <exception cref="ConversionTimedOutException">Raised when <see cref="conversionTimeout"/> is set and the
        /// conversion fails to finish in this amount of time</exception>
        /// <exception cref="DirectoryNotFoundException"></exception>
        public void ConvertToPdf(ConvertUri inputUri,
                                 string outputFile,
                                 PageSettings pageSettings,
                                 string waitForWindowStatus      = "",
                                 int waitForWindowsStatusTimeout = 60000,
                                 int?conversionTimeout           = null)
        {
            CheckIfOutputFolderExists(outputFile);
            using (var memoryStream = new MemoryStream())
            {
                ConvertToPdf(inputUri, memoryStream, pageSettings, waitForWindowStatus,
                             waitForWindowsStatusTimeout, conversionTimeout);

                using (var fileStream = File.Open(outputFile, FileMode.Create))
                {
                    memoryStream.Position = 0;
                    memoryStream.CopyTo(fileStream);
                }
            }
        }
Example #2
0
        ///// <summary>
        /////     Converts the given <paramref name="inputFile" /> to JPG
        ///// </summary>
        ///// <param name="inputFile">The inputfile to convert to PDF</param>
        ///// <param name="outputFile">The output file</param>
        ///// <param name="pageSettings"><see cref="PageSettings"/></param>
        ///// <returns>The filename with full path to the generated PNG</returns>
        ///// <exception cref="DirectoryNotFoundException"></exception>
        //public void ConvertToPng(string inputFile, string outputFile, PageSettings pageSettings)
        //{
        //    CheckIfOutputFolderExists(outputFile);
        //    _communicator.NavigateTo(new Uri("file://" + inputFile), TODO);
        //    SetDefaultArgument("--screenshot", Path.ChangeExtension(outputFile, ".png"));
        //}

        ///// <summary>
        /////     Converts the given <paramref name="inputUri" /> to JPG
        ///// </summary>
        ///// <param name="inputUri">The webpage to convert</param>
        ///// <param name="outputFile">The output file</param>
        ///// <returns>The filename with full path to the generated PNG</returns>
        ///// <exception cref="DirectoryNotFoundException"></exception>
        //public void ConvertToPng(Uri inputUri, string outputFile)
        //{
        //    CheckIfOutputFolderExists(outputFile);
        //    _communicator.NavigateTo(inputUri, TODO);
        //    SetDefaultArgument("--screenshot", Path.ChangeExtension(outputFile, ".png"));
        //}
        #endregion

        #region CheckForPreWrap
        /// <summary>
        ///     Checks if <see cref="PreWrapExtensions"/> is set and if the extension
        ///     is inside this list. When in the list then the file is wrapped
        /// </summary>
        /// <param name="inputFile"></param>
        /// <param name="outputFile"></param>
        /// <returns></returns>
        private bool CheckForPreWrap(ConvertUri inputFile, out string outputFile)
        {
            outputFile = inputFile.LocalPath;

            if (PreWrapExtensions.Count == 0)
            {
                return(false);
            }

            var ext = Path.GetExtension(inputFile.LocalPath);

            if (!PreWrapExtensions.Contains(ext, StringComparison.InvariantCultureIgnoreCase))
            {
                return(false);
            }

            outputFile = PreWrapper.WrapFile(inputFile.LocalPath, inputFile.Encoding);
            WriteToLog($"Prewraped file '{inputFile}' to '{outputFile}'");
            return(true);
        }
Example #3
0
        /// <summary>
        ///     Converts the given <paramref name="inputUri" /> to PDF
        /// </summary>
        /// <param name="inputUri">The webpage to convert</param>
        /// <param name="outputStream">The output stream</param>
        /// <param name="pageSettings"><see cref="PageSettings"/></param>
        /// <param name="waitForWindowStatus">Wait until the javascript window.status has this value before
        ///     rendering the PDF</param>
        /// <param name="waitForWindowsStatusTimeout"></param>
        /// <param name="conversionTimeout">An conversion timeout in milliseconds, if the conversion failes
        /// to finished in the set amount of time then an <see cref="ConversionTimedOutException"/> is raised</param>
        /// <exception cref="ConversionTimedOutException">Raised when <see cref="conversionTimeout"/> is set and the
        /// conversion fails to finish in this amount of time</exception>
        public void ConvertToPdf(ConvertUri inputUri,
                                 Stream outputStream,
                                 PageSettings pageSettings,
                                 string waitForWindowStatus      = "",
                                 int waitForWindowsStatusTimeout = 60000,
                                 int?conversionTimeout           = null)
        {
            if (inputUri.IsFile && !File.Exists(inputUri.OriginalString))
            {
                throw new FileNotFoundException($"The file '{inputUri.OriginalString}' does not exists");
            }

            FileInfo preWrappedFile = null;

            try
            {
                if (inputUri.IsFile && CheckForPreWrap(inputUri, out var preWrapFile))
                {
                    inputUri       = new ConvertUri(preWrapFile);
                    preWrappedFile = new FileInfo(preWrapFile);
                }
                else if (ImageResize || ImageRotate)
                {
                    if (!ImageHelper.ValidateImages(inputUri, ImageResize, ImageRotate, pageSettings, out var outputUri))
                    {
                        inputUri = outputUri;
                    }
                }

                StartChromeHeadless();

                CountdownTimer countdownTimer = null;

                if (conversionTimeout.HasValue)
                {
                    if (conversionTimeout <= 1)
                    {
                        throw new ArgumentOutOfRangeException($"The value for {nameof(countdownTimer)} has to be a value equal to 1 or greater");
                    }

                    WriteToLog($"Conversion timeout set to {conversionTimeout.Value} milliseconds");

                    countdownTimer = new CountdownTimer(conversionTimeout.Value);
                    countdownTimer.Start();
                }

                WriteToLog("Loading " + (inputUri.IsFile ? "file " + inputUri.OriginalString : "url " + inputUri));

                _communicator.NavigateTo(inputUri, countdownTimer);

                if (!string.IsNullOrWhiteSpace(waitForWindowStatus))
                {
                    if (conversionTimeout.HasValue)
                    {
                        WriteToLog("Conversion timeout paused because we are waiting for a window.status");
                        countdownTimer.Stop();
                    }

                    WriteToLog($"Waiting for window.status '{waitForWindowStatus}' or a timeout of {waitForWindowsStatusTimeout} milliseconds");
                    var match = _communicator.WaitForWindowStatus(waitForWindowStatus, waitForWindowsStatusTimeout);
                    WriteToLog(!match ? "Waiting timed out" : $"Window status equaled {waitForWindowStatus}");

                    if (conversionTimeout.HasValue)
                    {
                        WriteToLog("Conversion timeout started again because we are done waiting for a window.status");
                        countdownTimer.Start();
                    }
                }

                WriteToLog((inputUri.IsFile ? "File" : "Url") + " loaded");

                WriteToLog("Converting to PDF");

                using (var memorystream = new MemoryStream(_communicator.PrintToPdf(pageSettings, countdownTimer).Bytes))
                {
                    memorystream.Position = 0;
                    memorystream.CopyTo(outputStream);
                }

                WriteToLog("Converted");
            }
            finally
            {
                if (preWrappedFile != null)
                {
                    WriteToLog("Deleting prewrapped file");
                    preWrappedFile.Delete();
                }
            }
        }