Skip to content

PDF导出扩展 #519

@SummerZYQ

Description

@SummerZYQ

现在的PdfExporterAttribute很多打印属性无法自定义。比如根据实例属性设置不同的页眉页脚等
ps:下面代码临时凑活的,命名需要规范。

接口或抽象类

public abstract class ICustomPdfExporter
{
    public virtual void Configure(ref ObjectSettings o)
    {

    }
}

导出pdf时获取下

    public async Task<byte[]> ExportBytesByTemplateEx<T>(T data, string template) where T : class
    {
        var html = await _htmlExporter.ExportByTemplate(data, template);
        var pdfAttr = data.GetType().GetCustomAttribute<PdfExporterAttribute>() ?? new();

        var objSettings = new ObjectSettings
        {
            HtmlContent = html,
            Encoding = Encoding.UTF8,
            PagesCount = pdfAttr.IsEnablePagesCount ? true : (bool?)null,
            WebSettings = { DefaultEncoding = Encoding.UTF8.BodyName },
        };
        if (pdfAttr.HeaderSettings != null)
            objSettings.HeaderSettings = pdfAttr.HeaderSettings;

        if (pdfAttr.FooterSettings != null)
            objSettings.FooterSettings = pdfAttr?.FooterSettings;

        // 增加 复写打印设置
        if (data is ICustomPdfExporter data1)
        {
            data1.Configure(ref objSettings);
        }

        var htmlToPdfDocument = new HtmlToPdfDocument
        {
            GlobalSettings =
                {
                    PaperSize = pdfAttr!.PaperKind == PaperKind.Custom
                    ? pdfAttr.PaperSize : pdfAttr.PaperKind,
                    Orientation = pdfAttr.Orientation,
                    ColorMode = ColorMode.Color,
                    DocumentTitle = pdfAttr.Name,
                },
            Objects =
                {
                    objSettings
                }
        };

        if (pdfAttr.MarginSettings != null)
        {
            htmlToPdfDocument.GlobalSettings.Margins = pdfAttr.MarginSettings;
        }

        return PdfConverter.Convert(htmlToPdfDocument);

    }

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions