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#高级语法之线程与任务
开发语言·c#
weixin_307779132 小时前
C#实现两个DocumentDB实例之间同步数据
开发语言·数据库·c#·云计算
foundbug9992 小时前
基于C#的OPC DA客户端实现源码解析
开发语言·c#
Crazy Struggle4 小时前
.NET 中如何快速实现 List 集合去重?
c#·.net
xb11325 小时前
C#生产者-消费者模式
开发语言·c#
今晚打老虎z5 小时前
解决SQL Server 安装运行时针对宿主机内存不足2GB的场景
sqlserver·c#
Traced back6 小时前
# C# WinForms 数据库清理系统基础知识与避坑指南
开发语言·数据库·c#
我要打打代码8 小时前
关于C#线程 任务
开发语言·数据库·c#
Traced back8 小时前
# C# 基础语法完全指南
开发语言·c#
大黄说说9 小时前
TensorRTSharp 实战指南:用 C# 驱动 GPU,实现毫秒级 AI 推理
开发语言·人工智能·c#