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));
}
相关推荐
李建军1 小时前
界止签章宗地号替换工具
c#
qq_425263321 小时前
.net开发框架和语言
c#
武藤一雄2 小时前
C# 关于多线程如何实现需要注意的问题(持续更新)
windows·后端·microsoft·c#·.net·.netcore·死锁
flysh052 小时前
C# 架构设计:接口 vs 抽象类的深度选型指南
开发语言·c#
flysh053 小时前
C# 中类型转换与模式匹配核心概念
开发语言·c#
故事不长丨5 小时前
C#字典(Dictionary)全面解析:从基础用法到实战优化
开发语言·c#·wpf·哈希算法·字典·dictionary·键值对
wtsolutions7 小时前
Sheet-to-Doc占位符系统详解:让数据自动填入Word指定位置
开发语言·c#
kylezhao20198 小时前
C#上位机多语言切换实现
c#·工控上位机
我是唐青枫8 小时前
深入理解 System.Lazy<T>:C#.NET 延迟初始化与线程安全
c#·.net
zxy28472253018 小时前
利用C#对接BotSharp本地大模型AI Agent示例(2)
人工智能·c#·api·ai agent·botsharp