C# PDF转HTML字符串

需要nuget安装Aspose.PDF插件,本文使用23.10.0版本

一、获取PDF文件,通过Aspose.Pdf.Document 以Html格式 保存到某个路径;再读取该html返回字符串。

cs 复制代码
//html文件保存路径
string filePath = dirPath + "xxx.html";
if (!File.Exists(filePath))
{
    //获取pdf文件流
    Byte[] pdfByte = ......;
    var document = new Aspose.Pdf.Document(new MemoryStream(pdfByte));
    document.Save(filePath, SaveFormat.Html);
}

//读取刚刚保存的文件  
string file = File.ReadAllText(filePath);
string oldPath = "xxx_files";
string newPath = ConfigurationManager.AppSettings["NurseHtmlIP"] + "/" + oldPath;
//剔除版权文字;替换本地css和图片路径 为 http路径,使得在第三方接口可调用
string targetHtml = file.Replace("Evaluation Only. Created with Aspose.PDF. Copyright 2002-2023 Aspose Pty Ltd.","").Replace(oldPath, newPath);
return targetHtml;

二、在用Base64加密,避免格式错误。

cs 复制代码
string base64Html = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(targetHtml)));

三、前端显示,js方法。

cs 复制代码
//base64转字符串
function base64ToString(str) {
    return decodeURIComponent(atob(str).split('').map(function (c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));
}

var showInfo = function (htmlStr) {
    //把html显示到前端
    $("#ele_target").html(base64ToString(htmlStr));
}
相关推荐
码观天工16 分钟前
.NET 原生驾驭 AI 新基建实战系列(五):Milvus ── 大规模 AI 应用的向量数据库首选
c#·.net·milvus·向量数据库·高性能
XiaoyuEr_66881 小时前
C#中属性和字段的区别
开发语言·c#
火星papa1 小时前
C# 利用log4net 工作台打印和保存到文件
c#
ghost1431 小时前
C#学习第19天:多线程
开发语言·学习·c#
钢铁男儿1 小时前
C# 类的基本概念(声明类)
c#
李宥小哥2 小时前
Redis03-基础-C#客户端
开发语言·缓存·中间件·c#
姜行运4 小时前
数据结构【堆和链式结构】
数据结构·算法·c#
极小狐5 小时前
极狐GitLab 议题权重有什么作用?
开发语言·数据库·chrome·c#·gitlab
董先生_ad986ad8 小时前
C# 中的 `lock` 关键字本质
开发语言·c#