Chromium Embedded Framework(CEF)开发基础

Chromium Embedded Framework(CEF)开发基础

1 CEF3编译

1.1 Windows平台编译CEF

1.1.1 环境

OS: windows 11

开发环境: Visual Studio 2022

 1.1.2 下载官方预编译二进制库

为加快工程进度,避免从源码编译Chromium+CEF。本文使用官方提供的预编译二进制包。下载地址为:

https://cef-builds.spotifycdn.com/index.html

找到windows 64-bit 下稳定版本

image

 解压后,进入cef_binary目录。在cmd命令窗口构建工程:

mkdir build
cd build
cmake -G "Visual Studio 17 2022" -A x64 ..

构建完毕后,可以在build目录下看到名为cef.sln的Visual Studio解决方案文件:

image

 用visual studio 2022打开,并编译全部工程:

image

 编译完成后,就可以挪到项目中使用了。

1.2 Linux平台编译CEF

mkdir build
cd build
cmake  ..

 2 .netcore 调用CEF

os:debian 12

dotnet version: 9.0.310

2.1 安装dotnet-sdk-9.0

# 安装必要工具
sudo apt update
sudo apt install -y wget apt-transport-https software-properties-common
wget https://packages.microsoft.com/config/debian/12/packages-microsoft-prod.deb -O packages-microsoft-prod.deb
sudo dpkg -i packages-microsoft-prod.deb
rm packages-microsoft-prod.deb

sudo apt update

sudo apt install -y dotnet-sdk-9.0

dotnet --version

2.2 amd64平台实现html页面打印pdf

PuppeteerSharp 是一个纯 .NET 库,它对 .NET 的版本要求只要是较新 SDK 就可以正常工作(包括 .NET 9.0)。安装了 .NET 9.0 SDK 后你就可以像下面这样写 PuppeteerSharp 代码生成 PDF:

dotnet new console -n HtmlToPdf
cd HtmlToPdf
dotnet add package PuppeteerSharp

安装完整中文字体

sudo apt update

sudo apt install -y \
 fonts-noto-cjk \
 fonts-noto-color-emoji \
 fonts-dejavu \
 fonts-liberation \
 fonts-wqy-zenhei \
 fonts-wqy-microhei

刷新字体

fc-cache -fv

编写业务代码

using PuppeteerSharp;
using PuppeteerSharp.Media;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        Console.WriteLine("Start PDF generation...");
       
        var fetcherOptions = new BrowserFetcherOptions //首次启动时,下载Chromium
        {
            Path = "./.local-chromium" 
        };

        var browserFetcher = Puppeteer.CreateBrowserFetcher(fetcherOptions);
      
        await browserFetcher.DownloadAsync(); //下载最新可用版本
        
        await using var browser = await Puppeteer.LaunchAsync(new LaunchOptions
        {
            Headless = true 
        });
     
        await using var page = await browser.NewPageAsync();
       
       // await page.GoToAsync("https://www.baidu.com/");

       await page.GoToAsync("file:///opt/work/tempHtml7297372055792989837.html");
       // await page.GoToAsync("file:///opt/work/dotnet/htmltopdf/tempHtml1120868243207249364.html");
         await page.AddStyleTagAsync(new AddTagOptions
        {
            Content = @"
            * {
                font-family:
                    'Noto Sans CJK SC',
                    'Microsoft YaHei',
                    'SimSun',
                    'WenQuanYi Zen Hei',
                    sans-serif !important;
            }"
        });
        await page.PdfAsync(
            "output1.pdf",
            new PdfOptions
            {
                PrintBackground = true,
               // PreferCSSPageSize = true,
               // Format = PaperFormat.A4,            
                MarginOptions = new MarginOptions
                {
                    Top = "20mm",      // 上边距
                    Bottom = "20mm",   // 下边距
                    Left = "30mm",     // 左边距
                    Right = "30mm"     // 右边距
                }         
            }
        );

        Console.WriteLine("PDF generated: output.pdf");
    }
}

 Docker/服务器部署时,安装字体方法:

RUN apt-get update && apt-get install -y \
    fonts-noto-cjk \
    fonts-wqy-zenhei \
    fonts-dejavu \
    fonts-liberation \
    && fc-cache -fv

 2.3 aarch64平台实现html页面打印pdf

本文在qemu模拟器下操作,所以需要挂载目录如下:

mount --bind /proc ./debian-rootfs/proc
mount --bind /sys  ./debian-rootfs/sys
mount --bind /dev ./debian-rootfs/dev
mount --bind /run  ./debian-rootfs/run
mount -o remount,size=1G /dev/shm  #重要,不要遗漏

安装字体

sudo apt update

sudo apt install -y \
 fonts-noto-cjk \
 fonts-noto-color-emoji \
 fonts-dejavu \
 fonts-liberation \
 fonts-wqy-zenhei \
 fonts-wqy-microhei

刷新字体

fc-cache -fv

下载.net 6.0 SDK-Linux Arm64

https://builds.dotnet.microsoft.com/dotnet/Sdk/6.0.428/dotnet-sdk-6.0.428-linux-arm64.tar.gz

部署

mkdir -p $HOME/dotnet && tar zxf dotnet-sdk-6.0.428-linux-arm64.tar.gz -C $HOME/dotnet
export DOTNET_ROOT=$HOME/dotnet
export PATH=$PATH:$HOME/dotnet

The previous commands will only make the .NET SDK commands available for the terminal session in which it was run.

You can edit your shell profile to permanently add the commands. There are several different shells available for Linux and each has a different profile. For example:

  • Bash Shell: ~/.bash_profile, ~/.bashrc
  • Korn Shell: ~/.kshrc or .profile
  • Z Shell: ~/.zshrc or .zprofile

Edit the appropriate source file for your shell and add :$HOME/dotnet to the end of the existing PATH statement. If no PATH statement is included, add a new line with export PATH=$PATH:$HOME/dotnet.

Also add export DOTNET_ROOT=$HOME/dotnet to the end of the file.

安装Chromium+依赖:

sudo apt update

sudo apt install -y chromium \
  libnss3 \
  libatk1.0-0 \
  libatk-bridge2.0-0 \
  libcups2 \
  libx11-xcb1 \
  libxcomposite1 \
  libxdamage1 \
  libxrandr2 \
  libgbm1 \
  libpango-1.0-0 \
  libgtk-3-0 \
  libasound2 \
  libxshmfence1 \
  libxss1 \
  fonts-liberation \
  xdg-utils

编译业务代码(稍微与amd64环境有区别)

using PuppeteerSharp;
using PuppeteerSharp.Media;
using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        Console.WriteLine("Start PDF generation...");
       
        var fetcherOptions = new BrowserFetcherOptions 
        {
            Path = "./.local-chromium" 
        };

        var browserFetcher = Puppeteer.CreateBrowserFetcher(fetcherOptions);
        //await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision, BrowserFetcher.Platform.LinuxArm64); 
        //await browserFetcher.DownloadAsync(); 
        
        await using var browser = await Puppeteer.LaunchAsync(new LaunchOptions
        {
            Headless = true ,
        ExecutablePath = "/usr/bin/chromium",
        Args = new[]
        {
            "--no-sandbox",
            "--disable-setuid-sandbox",
            "--disable-dev-shm-usage",
            "--disable-gpu",
            "--single-process",
            "--no-zygote",
            "--no-first-run",
            "--disable-features=VizDisplayCompositor"
        }

        });
     
        await using var page = await browser.NewPageAsync();
       
       // await page.GoToAsync("https://www.baidu.com/");

       //await page.GoToAsync("file:///opt/work/tempHtml7297372055792989837.html");
        await page.GoToAsync("file:///opt/work/tempHtml1120868243207249364.html");
         await page.AddStyleTagAsync(new AddTagOptions
        {
            Content = @"
            * {
                font-family:
                    'Noto Sans CJK SC',
                    'Microsoft YaHei',
                    'SimSun',
                    'WenQuanYi Zen Hei',
                    sans-serif !important;
            }"
        });
        await page.PdfAsync(
            "output1.pdf",
            new PdfOptions
            {
                PrintBackground = true,
               // PreferCSSPageSize = true,
               // Format = PaperFormat.A4,            
                MarginOptions = new MarginOptions
                {
                    Top = "20mm",    
                    Bottom = "20mm",   
                    Left = "30mm",   
                    Right = "30mm"     
                }         
            }
        );

        Console.WriteLine("PDF generated: output.pdf");
    }
}

 

posted @ 2026-02-04 11:27  钟齐峰  阅读(7)  评论(0)    收藏  举报