如何使用wkhtmltopdf.exe制作关于div高度和宽度的pdf文件大小

时间:2011-12-24 07:43:12

标签: vb.net wkhtmltopdf

我尝试通过提供html字符串来制作带有wkhtmltopdf.exe的pdf并且工作正常。但我想为exe提供pdf自定义大小。

例如: -    假设我有一个高度为30且宽度为50的div。那么生成的pdf应该是相同的大小。

以下是我在本网站论坛上找到的代码

     Private Sub WritePDF(ByVal HTML As String)
    Dim inFileName As String, outFileName As String, tempPath As String
    Dim p As Process
    Dim stdin As System.IO.StreamWriter
    Dim psi As New ProcessStartInfo()

    tempPath = Server.MapPath("~") + "\Uploads\"
    inFileName = Session.SessionID + ".htm"
    outFileName = Session.SessionID + ".pdf"

    ' run the conversion utility 
    psi.UseShellExecute = False
    'psi.FileName = "c:\Program Files (x86)\wkhtmltopdf\wkhtmltopdf.exe"
    psi.FileName = Server.MapPath("~") + "\App_Data\wkhtmltopdf.exe"
    psi.CreateNoWindow = True
    psi.RedirectStandardInput = True
    psi.RedirectStandardOutput = True
    psi.RedirectStandardError = True


    ' note that we tell wkhtmltopdf to be quiet and not run scripts 
    ' NOTE: I couldn't figure out a way to get both stdin and stdout redirected so we have to write to a file and then clean up afterwards 
    psi.Arguments = "-q -n - " & tempPath & outFileName

    p = Process.Start(psi)

    Try
        stdin = p.StandardInput
        stdin.AutoFlush = True

        stdin.Write(HTML)
        stdin.Close()

        If p.WaitForExit(15000) Then
            ' NOTE: the application hangs when we use WriteFile (due to the Delete below?); this works 
            'Response.WriteFile(tempPath + outFileName); 
            Response.BinaryWrite(System.IO.File.ReadAllBytes(tempPath & outFileName))
        End If
    Finally
        p.Close()
        p.Dispose()
    End Try

    ' delete the pdf 
    System.IO.File.Delete(tempPath & outFileName)
End Sub

1 个答案:

答案 0 :(得分:2)

如果要使用标准纸张尺寸,可以使用--page-size参数并提供页面尺寸名称(A4,Letter等)。如果需要自定义页面大小,可以使用--page-width和--page-height参数(例如--page-width 100mm --page-height 200mm)。

默认情况下,wkhtmltopdf会在页面的每一边添加一个边距,用于渲染页眉和页脚。要更改页边距,请使用参数--margin-top, - margin-right, --margin-bottom和--margin-left。

需要注意的另一件事是--disable-smart-shrinking;默认情况下,wkhtmltopdf将通过计算html宽度并尝试将其置于pdf页面的边界内来“猜测”pdf的dpi。如果要精确测量页面上的每个元素,则应将--disable-smart-shrinking添加到参数列表中。但是,请确保html输出定义html页面的确切大小(应该与pdf页面相同,减去页面边距),否则wkhtmltopdf可能无法正确呈现页面。