vbapdf

Export html content to pdf using Microsoft Edge


I have this working code that converts HTML file to pdf by printing through command line using Microsft Edge

Sub Test()
    Dim fso As Object, wshShell As Object, sPath As String, sHTMLFile As String, sPDFFile As String, sCommand As String
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set wshShell = CreateObject("WScript.Shell")
    sPath = ThisWorkbook.Path & Application.PathSeparator
    sHTMLFile = sPath & "Sample.html"
    sPDFFile = sPath & "Sample.pdf"
    If Not fso.FileExists(sHTMLFile) Then MsgBox "HTML File Not Found: " & sHTMLFile, vbExclamation: GoTo CleanUp
    sCommand = "msedge --headless --disable-gpu --print-to-pdf=""" & sPDFFile & """ """ & sHTMLFile & """"
    wshShell.Run sCommand, 0, True
    If fso.FileExists(sPDFFile) Then
        MsgBox "PDF Exported Successfully To:" & vbNewLine & sPDFFile, 64
    Else
        MsgBox "Not Exported", 48
    End If
CleanUp:
    Set wshShell = Nothing: Set fso = Nothing
End Sub

The code is working but takes about 7 seconds and I have a bulk of files (about 100 files). Is there a way to make it faster or is there an alternative methods ?


Solution

  • To programmatical use the same fast system as provided for developers by chromium applications.

    You can use a replacement for the inbuilt MS Edge with Chrome-headless-shell as their preferred lighter (thus supposedly faster) alternative.

    There are several ways to download exceptionally quickly using native CMD and CURL (not PowerShell) as there is a distinct difference in timing on some Windows hardware.

    To speed up the calls use a batch file of addresses should help

    start "" Chrome-headless-shell.exe --print-to-pdf="%CD%\%~1.pdf" "%~2.html"
    

    There is no need to disable high speed GPU. So remove that switch and you can use others such as --no-pdf-header-footer.

    To download the Chromium Recommended current exe use the script under "New Answer" or similar https://stackoverflow.com/a/76079607/10802527