locked
How to use Codaxy.WkHtmlToPdf RRS feed

  • Question

  • User-560223997 posted

    I am using this C# converter from html to pdf.

    In the .csproj I have:

      <ItemGroup>
        <PackageReference Include="Codaxy.WkHtmlToPdf" Version="0.5.8" />
      </ItemGroup>
    

    I want to use in the controller something like:

                PdfConvert.ConvertHtmlToPdf(new PdfDocument
                {
                    Url = "http://wkhtmltopdf.org/",
                    HeaderLeft = "[title]",
                    HeaderRight = "[date] [time]",
                    FooterCenter = "Page [page] of [topage]"
    
                }, new PdfOutput
                {
                    OutputFilePath = "wkhtmltopdf-page.pdf"
                });

    (this is the same code as in GitHub).

    However, when I do (in the same controller):

    using Codaxy.WkHtmlToPdf;
    

    the project doesn't build (and shows error in the VS editor...). The error presented is:

    Error	CS0246	The type or namespace name 'Codaxy' could not be found (are you missing a using directive or an assembly reference?)

    The GitHub page of the project lacks directions on using using directive....

    Could you help me?

    Thursday, July 9, 2020 10:25 AM

All replies

  • User-943250815 posted

    Don´t know Codaxy.WkHtmlToPdf, if it help here is how I do it, this code has been translated from VB to C# hope it work for you

    protected void Button1_Click(object sender, EventArgs e)
    {
        string WorkingDirectory = @"c:\users\username\downloads";         // Set it for your correct path
        string WkExeFile = @"c:users\username\downloads\wkhtmltopdf.exe"; // Set it for your correct path
        string fail = null;
        try
        {
            byte[] URIToPDF = zConvertHtmlToPdfDile(new Uri("https://forums.asp.net"), WorkingDirectory, WkExeFile, "1", null, false);
            File.WriteAllBytes(@"c:\users\jzero\downloads\cebola.pdf", URIToPDF);
        }
        catch (Exception ex)
        {
            fail = ex.Message;
        }
    }
    
    public static byte[] zConvertHtmlToPdfDile(Uri pURL, string pWkDir, string pWkExe, string pWkZoom = "1", CookieCollection pCookies = null, bool pUsePrintMediaType = false)
    {
        StringBuilder args = new StringBuilder();
        {
            var withBlock = args;
            withBlock.Append("--quiet ");                                          // -q, --quiet               : Be less verbose, maintained for backwards compatibility; Same As Using --log-level none
            .Append("--disable-javascript ")                                       // -n, --disable-javascript  : Do not allow web pages to run javascript
            //.Append("--disable-smart-shrinking ")                                  // --disable-smart-shrinking : Disable the intelligent shrinking strategy used by WebKit that makes the pixel/dpi ratio none constant
            //.Append("--enable-smart-shrinking ")                                   // --enable-smart-shrinking  : Enable the intelligent shrinking strategy used by WebKit that makes the pixel/dpi ratio none constant (default)
            if (pWkZoom != null)
            {
                if (pWkZoom != string.Empty)
                    withBlock.Append("--zoom " + pWkZoom + " ");                   // --zoom <float> : Use this zoom factor (default 1)")
            }
            if (pCookies != null)
            {
                foreach (Cookie zCookie in pCookies)
                    withBlock.Append("--cookie " + zCookie.Name + " " + zCookie.Value + " ");
            }
            if (pUsePrintMediaType == true)
                withBlock.Append("--print-media-type ");
            withBlock.Append("--page-size A4 ");                                          // -s, --page-size <Size>    : Set paper size to: A4, Letter, etc. (default A4)
            withBlock.Append(pURL);                                                       // URL
            withBlock.Append(" -");                                                       // The dash - in the wkhtmltopdf command means that it takes it's input from stdin and not a file.
        }
        ProcessStartInfo processStartInfo = new ProcessStartInfo();                        
        {
            var withBlock = processStartInfo;
            withBlock.FileName = pWkExe;                                                  // Fullpath wkHtmlToPDf
            withBlock.WorkingDirectory = pWkDir;                                          // Working Directory for wkHtmlToPDf
            withBlock.Arguments = args.ToString();                                        // Argument command line
            withBlock.UseShellExecute = false;                                            
            withBlock.CreateNoWindow = true;                                              
            withBlock.RedirectStandardInput = true;                                       // Redirecionar input
            withBlock.RedirectStandardOutput = true;                                      // Redirecionar output
            withBlock.RedirectStandardError = true;                                       // Redirecionar erro
        }
        Process process__1 = Process.Start(processStartInfo);
        byte[] buffer = new byte[32768] { };
        byte[] file;
        using (var memoryStream = new MemoryStream())
        {
            while (true)
            {
                int read = process__1.StandardOutput.BaseStream.Read(buffer, 0, buffer.Length);
                if (read <= 0)
                    break;
                memoryStream.Write(buffer, 0, read);
            }
            file = memoryStream.ToArray();
        }
        process__1.StandardOutput.Close();
        process__1.WaitForExit(60000);       
        int returnCode = process__1.ExitCode;
        process__1.Close();
        process__1.Dispose();
        if (returnCode == 0 || returnCode == 1)
            return file;
        else
            throw new Exception(string.Format("Could not create PDF, returnCode:{0}", returnCode));
    }
    

    Thursday, July 9, 2020 6:44 PM