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));
}
相关推荐
32码奴1 小时前
C#基础知识
开发语言·c#
来恩100310 小时前
C# 类与对象详解
开发语言·c#
Dr.勿忘13 小时前
C#面试常考随笔8:using关键字有哪些用法?
开发语言·unity·面试·c#·游戏引擎
xcLeigh13 小时前
WPF进阶 | WPF 数据绑定进阶:绑定模式、转换器与验证
c#·wpf
谢大旭13 小时前
ASP.NET Core 中间件
后端·中间件·c#
时光追逐者14 小时前
Visual Studio使用GitHub Copilot提高.NET开发工作效率
c#·github·.net·copilot·ai编程·微软技术·visual studio
唐青枫16 小时前
dotnet LINQ 使用简明教程
c#·.net
谢大旭17 小时前
.Net Web API 访问权限限定
开发语言·c#
幻想趾于现实19 小时前
如何用函数去计算x年x月x日是(C#)
开发语言·c#
我命由我123451 天前
游戏引擎 Unity - Unity 下载与安装
c语言·开发语言·c++·后端·unity·c#·游戏引擎