CWebView::SaveDocument Method  
 
BOOL SaveDocument(
  UINT uFileType,  
  LPCTSTR lpszFileName  
);
BOOL SaveDocument(
  UINT uFileType,  
  LPCTSTR lpszFileName,  
  LPWEBVIEW_PRINT_SETTINGS lpSettings  
);

The SaveDocument method saves the current document to a local file, with options to control page dimensions, margins, scaling, orientation, backgrounds, and headers and footers when saving as PDF.

Parameters

uFileType
An unsigned integer which specifies the format the document should be saved as.
Value Description
WEBVIEW_FILE_TYPE_DEFAULT Save using a format inferred from the file extension. If the file extension is not recognized, the contents will be saved as plain text. For example, if you specify a file name with the .html extension, it will be saved in HTML format. If the file name has a .pdf extension, it will be saved as a PDF.
WEBVIEW_FILE_TYPE_TEXT Saves the current document as plain text. The HTML tags are removed and entities are converted to their UTF-8 equivalent. Extraneous whitespace within the text will be removed, but the overall structure of ordered and unordered lists will be preserved. Choose this format if you wish to save only the text content of a document.
WEBVIEW_FILE_TYPE_HTML Saves the current document as a UTF-8 encoded HTML file. This includes the complete source for the page, but does not include any of the additional assets such as images. Choose this format if you wish to save the document as an editable HTML file.
WEBVIEW_FILE_TYPE_JSON Saves the current document as a JSON formatted string. The string will be quoted and reserved characters will be escaped. Choose this format if you wish to preserve the HTML document as a JSON string for logging or embedding in a JSON object.
WEBVIEW_FILE_TYPE_MHTML Saves the current document as a single-file web archive (MHTML) that inlines the HTML content and all of the resources it references. This format calls the DevTools Page.captureSnapshot method in the browser and writes the returned data to disk. MHTML is useful for offline archiving since it combines images, styles and scripts together in a single file.
WEBVIEW_FILE_TYPE_PDF Saves the current document as a PDF file which produces a paginated document suitable for printing and distribution. This is functionally similar to using the browser to print to a PDF, but does not display a dialog to the user. The lpSettings parameter can specify formatting options.
WEBVIEW_FILE_TYPE_JPEG Save the current document view as a JPEG image. JPEG is a widely used image format optimized for photographs and complex images with smooth gradients. It uses lossy compression to significantly reduce file size while maintaining acceptable visual quality.
WEBVIEW_FILE_TYPE_PNG Save the current document view as a PNG image. PNG is a lossless image format designed for crisp detail and high fidelity, especially in graphics with sharp edges, text, or flat colors. Although PNG files are typically larger than JPEGs, they preserve exact image data without quality loss.
WEBVIEW_FILE_TYPE_WEBP Save the current document view as a WebP image. WebP is a modern image format developed by Google that supports both lossy and lossless compression, as well as transparency and animation. It delivers smaller file sizes compared to JPEG and PNG while maintaining comparable or better visual quality.
lpszFileName
A null-terminated string which specifies the name of the local file. If the path includes environment variables enclosed in percent (%) symbols, the variables will be expanded. This parameter cannot be NULL and must specify a valid file path. The file name cannot specify a device, folder name or system file. If the file is marked as read-only, the method will fail.
lpSettings
A pointer to a WEBVIEW_PRINT_SETTINGS structure which controls PDF formatting. Initialize the structure to zero, then set its dwSize member to sizeof(WEBVIEW_PRINT_SETTINGS) and specify the required settings. If this parameter is NULL, default PDF settings are used. This parameter must be omitted or NULL unless the selected output format is PDF, either explicitly or as determined from the file extension.

Return Value

If the method succeeds, the return value is non-zero. If the method fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

The SaveDocument method saves the current page to a local file in the format specified by the uFileType parameter. The operation is synchronous, processing messages while the browser completes the action, and only returns once the document has been created or the operation has failed. A temporary file is created during the save process and then moved into place, replacing any existing file. This ensures that an existing file will not be changed unless the browser indicates the save operation was successful. Saving is not permitted while a navigation is in progress, and attempts to do so will fail with an error.

The file name specified must be valid, and environment variables in the path are expanded before use. When WEBVIEW_FILE_TYPE_DEFAULT is specified, the format is inferred from the file extension. For example, .html or .htm will save the document as HTML, .pdf will create a PDF file and .png will save the page as a PNG image. If no recognized extension is present, the page will be saved as plain text by default.

When saving the current document as plain text, the HTML markup will be removed and it will be saved as a UTF-8 encoded text file. When saving as HTML, the method saves the complete HTML source for the page. The JSON format also saves the HTML markup, but encodes it as a quoted JSON string with reserved characters escaped. Note that all text-related formats are saved using UTF-8 multi-byte encoding without a byte order mark (BOM). The text will not be automatically converted to the current user's locale. Most modern text editors automatically recognize UTF-8 encoding, but some legacy applications may assume the text is localized to the current code page.

The MHTML option creates a single-file archive which contains the page content and all of its resources such as images, style sheets, and scripts. This format is often used for offline archiving or sharing since everything is contained in one file. Saving as PDF renders the page into a paginated print-style format suitable for distribution. These formats all operate on the complete document, including content that extends beyond the visible area.

By contrast, saving as an image (JPEG, PNG, or WebP) captures only the visible viewport of the page at the time the method is called. Content that requires scrolling will not be included in the saved image. PNG is lossless and preserves transparency, while JPEG and WebP use compression to produce smaller files. WEBP generally offers better quality at a reduced size compared to JPEG, but support for the format may vary between applications. If you want a pixel-perfect representation of the current page as it appears on the screen, particularly if it contains a lot of text, it is recommended that you use the PNG format.

Because this method blocks the current thread until the save completes, it may take a noticeable amount of time to return if the current document is very large. If the method is called from a worker thread, the request is marshaled to the UI thread that manages the browser control. For applications with a graphical interface, it is recommended that you display the standard hourglass (or other busy indicator) while the save is in progress to provide a visual cue to the user.

When saving a document as a PDF without providing any print settings, this method uses the default print settings provided by the Microsoft Edge WebView2 runtime. These defaults include portrait orientation, US Letter paper size (8.5 × 11 inches), a scale factor of 100%, and margins of approximately 0.4 inches on all sides. Background colors and images are not printed, and headers and footers are enabled by default. The resulting PDF includes all pages of the document.

When saving the document as a PDF with print settings, the WEBVIEW_PRINT_SETTINGS structure can be used to control page dimensions, margins, scaling, orientation, background colors and images, and headers and footers. The flags in the structure's dwFlags member determine which optional settings are applied:

  • WEBVIEW_PRINT_FLAG_PAGE_SIZE applies dPageWidth and dPageHeight, in inches. Each invalid dimension is replaced with the corresponding library default.
  • WEBVIEW_PRINT_FLAG_MARGINS applies all four margin members, in inches. Zero requests no margin; invalid values are converted to zero.
  • WEBVIEW_PRINT_FLAG_SCALE applies dScale. A value of 1.0 represents 100 percent. Non-zero values are limited to the range 0.1 through 2.0. Zero or an invalid value leaves the default scale unchanged.
  • WEBVIEW_PRINT_FLAG_BACKGROUND includes document background colors and images. Backgrounds are omitted when this flag is not specified.
  • WEBVIEW_PRINT_FLAG_HEADERS includes both a header and a footer. The lpszHeaderText and lpszFooterText members can specify custom text. Headers and footers are omitted when this flag is not specified.

The nOrientation member selects portrait or landscape orientation independently of dwFlags. Setting page dimensions, margins, or scaling without the corresponding flag has no effect. In particular, zero-initialized margins specify no margins when WEBVIEW_PRINT_FLAG_MARGINS is enabled; they do not request the default margins.

When headers and footers are enabled, a NULL lpszHeaderText uses the document title, and a NULL lpszFooterText uses the document URI. An empty string suppresses the corresponding text without disabling the other header or footer elements. Allow suitable top and bottom margins for this content.

Printer-specific structure members are ignored when saving directly to PDF. These members are nColorMode, nCopies, nDuplex, nPagesPerSide, nCollation, lpszPrinter, and lpszRanges. Consequently, these settings cannot request grayscale PDF output, restrict the PDF to a page range, or place multiple document pages on each PDF page.

PDF output renders the complete document using the browser's print layout, including content beyond the visible browser area. The document's print styles can affect its appearance and pagination. PDF output can therefore differ from the page as displayed on the screen.

If you want a copy of the HTML or plain text contents of the current page without saving it to a file, use the GetDocumentText or GetFilteredText methods.

If you wish to save the document as a PDF to memory and don't want the intermediate step of saving it to disk, the SaveDocumentToMemory method can be used to copy the document to a buffer that your application provides. This requires Microsoft Edge WebView2 Runtime version 109.0.1518.0 or later. Earlier versions of the runtime do not support the PrintToPdfStream method used to generate PDF documents in memory. If the installed runtime does not support this functionality, the method fails with the error code ST_ERROR_OPERATION_NOT_SUPPORTED.

Example

The following example saves the current document as a PDF using an explicit US Letter page size, portrait orientation, half-inch margins, and 100 percent scaling. Background colors and images are included. Headers and footers are omitted. The lpszFileName parameter must specify a valid destination file path.

WEBVIEW_PRINT_SETTINGS settings = { 0 };

settings.dwSize = sizeof(settings);
settings.dwFlags = WEBVIEW_PRINT_FLAG_PAGE_SIZE |
                   WEBVIEW_PRINT_FLAG_MARGINS |
                   WEBVIEW_PRINT_FLAG_SCALE |
                   WEBVIEW_PRINT_FLAG_BACKGROUND;

settings.dPageWidth = 8.5;
settings.dPageHeight = 11.0;

settings.dMarginLeft = 0.5;
settings.dMarginTop = 0.5;
settings.dMarginRight = 0.5;
settings.dMarginBottom = 0.5;

settings.dScale = 1.0;
settings.nOrientation = WEBVIEW_PRINT_ORIENTATION_PORTRAIT;

if (!pWebView->SaveDocument(WEBVIEW_FILE_TYPE_PDF, lpszFileName, &settings))
{
    DWORD dwError = WebViewGetLastError();

    // Report or otherwise handle dwError here
    return FALSE;
}

Requirements

Minimum Desktop Platform: Windows 7 Service Pack 1
Minimum Server Platform: Windows Server 2008 R2 Service Pack 1
Header File: cstools12.h
Import Library: cshtmv12.lib
Unicode: Implemented as Unicode and ANSI versions

See Also