Pregunta

Sé que esta herramienta mira hacia arriba en una dirección URL y convierte la repsponse a pdf. ¿Cómo se convierte un

<html> content.. </html> 

en un pdf?

yo estaba buscando en los archivos de ayuda en wkhtml2pdf y parece que ofrece una opción de entrada estándar, pero en realidad no puedo encontrar la manera de emular la entrada estándar.

Además, si usted conoce a una herramienta que hace un mejor trabajo, por favor, me sugieren algunos.

Muchas gracias!

¿Fue útil?

Solución

wkhtmltopdf es una herramienta gratuita, pero no está escrito en .NET y que podría ser un poco difícil de integrar en su aplicación asp.net.

Puede echar un vistazo a iTextSharp , que es gratuito, pero no puede manejar cualquier tipo de html , o se puede echar un vistazo a las herramientas comerciales para convertir hTML a PDF, como ExpertPDF o ABCpdf , que puede manejar cualquier html / css.

Otros consejos

acabo de empezar un nuevo proyecto para proporcionar una envoltura C # P / Invoke alrededor wkhtmltopdf.

Puedes retirar mi código en: https://github.com/pruiz/WkHtmlToXSharp

saluda.

Tome un vistazo a Pechkin

.NET Envoltura para wkhtmltopdf DLL, biblioteca que utiliza el motor Webkit para páginas convertir HTML a PDF.

paquetes Nuget:

Pechkin.Synchronized

Pechkin

Ejemplo código:

private void ConvertToPdf()
{
    var loadPath = Server.MapPath("~/HtmlTemplates");
    var loadFile = Path.Combine(loadPath, "Test.html");
    var savePath = Server.MapPath("~/Pdf");
    var saveFile = Path.Combine(savePath, DateTime.Now.ToString("HH-mm-ss.fff") + ".pdf");

    var globalConfig = new GlobalConfig()
        .SetMargins(0, 0, 0, 0)
        .SetPaperSize(PaperKind.A4);

    var pdfWriter = new SynchronizedPechkin(globalConfig);

    pdfWriter.Error += OnError;
    pdfWriter.Warning += OnWarning;

    var objectConfig = new ObjectConfig()
        .SetPrintBackground(true)
        .SetIntelligentShrinking(false);

    var pdfBuffer = pdfWriter.Convert(objectConfig, File.ReadAllText(loadFile));

    File.WriteAllBytes(saveFile, pdfBuffer);
}

private void OnWarning(SimplePechkin converter, string warningtext)
{
    throw new NotImplementedException();
}

private void OnError(SimplePechkin converter, string errortext)
{
    throw new NotImplementedException();
}

He encontrado una manera. Puede configurar otro para dar salida al HTML normal. Y utilizar esa URL como el valor de entrada del proceso wkhtml2pdf.

---------- Editar

public byte[] WKHtmlToPdf(string url_input)
    {
        try
        {
            var fileName = " - ";
            var wkhtmlDir = ConfigurationSettings.AppSettings["wkhtmlDir"];
            var wkhtml = ConfigurationSettings.AppSettings["wkhtml"];
            var p = new Process();

            string url = Request.Url.GetLeftPart(UriPartial.Authority) + @"/application/" + url_input;

            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.FileName = wkhtml;
            p.StartInfo.WorkingDirectory = wkhtmlDir;

            string switches = "";
            switches += "--print-media-type ";
            switches += "--margin-top 10mm --margin-bottom 10mm --margin-right 10mm --margin-left 10mm ";
            switches += "--page-size Letter ";
            p.StartInfo.Arguments = switches + " " + url + " " + fileName;
            p.Start();

            //read output
            byte[] buffer = new byte[32768];
            byte[] file;
            using (var ms = new MemoryStream())
            {
                while (true)
                {
                    int read = p.StandardOutput.BaseStream.Read(buffer, 0, buffer.Length);

                    if (read <= 0)
                    {
                        break;
                    }
                    ms.Write(buffer, 0, read);
                }
                file = ms.ToArray();
            }

            // wait or exit
            p.WaitForExit(60000);

            // read the exit code, close process
            int returnCode = p.ExitCode;
            p.Close();

            return returnCode == 0 ? file : null;
        }
        catch (Exception ex)
        {

           // set your exceptions here
            return null;
        }
    }

---------- web.config ejemplo clave

  <add key="wkhtmlDir" value="C:\Program Files (x86)\wkhtmltopdf\bin"/>
    <add key="wkhtml" value="C:\Program Files (x86)\wkhtmltopdf\bin\wkhtmltopdf.exe"/>

La idea básica está pasando url para el exe como argumento.

HTH!

si desea imprimir parte específica del HTML con CSS

instalar paquetes Nuget:

Pechkin.Synchronized

StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
  pnlprint.RenderControl(hw);
    StringReader sr = new StringReader(sw.ToString());
   string cssPath = Server.MapPath("~/css/style1.css");

    string cssString = File.ReadAllText(cssPath);
     cssPath = Server.MapPath("~/css/bootstrap.css");
    string cssString2 = File.ReadAllText(cssPath);
    cssString += cssString2;
    GlobalConfig gc = new GlobalConfig();
    byte[] pdfContent = new SimplePechkin(new GlobalConfig()).Convert(@"<html><head><style>" + cssString + "</style></head><body>" + sw.ToString() + "</body></html>");

Aquí puede entender fácilmente el funcionamiento de wkhtmltopdf https://ourcodeworld.com/articles/read/366/how-to-generate-a-pdf-from-html-using -wkhtmltopdf-con-c-en-winforms

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top