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));
}
相关推荐
周杰伦fans3 小时前
C# 踩坑 CS8370:Switch Expression 在 C# 7.3 不可用及三种解决方案
c#
z落落5 小时前
C# ToCharArray + foreach遍历 + String与StringBuilder
开发语言·c#
xiaoshuaishuai86 小时前
C# AvaloniaUI动态显示图片
开发语言·c#
csdn_aspnet9 小时前
EasyModbus 与 C# 集成
c#·modbus·easymodbus
JaydenAI11 小时前
[MAF预定义ChatClient中间件-06]利用ImageGeneratingChatClient开发专业图片生成Agent
ai·c#·agent·agent管道·chatclient中间件·chatclient管道
csdn_aspnet12 小时前
Modbus TCP C# 客户端程序
服务器·网络·tcp/ip·c#
0x000713 小时前
译 Anders Hejlsberg 谈 C# 与 .NET
开发语言·c#·.net
Xin_ye1008613 小时前
C# 零基础到精通教程 - 第十七章:前端集成——Blazor 基础
开发语言·c#
daopuyun13 小时前
《C#语言源代码漏洞测试规范》解读,如何依据GB/T 34946-2017标准建立代码测试技术体系
c#·代码测试·源代码安全检测