C#使用iTextSharp将图片转为pdf
最近接到的工作
1.word转PDF
3.JPG转PDF
在NuGet里面搜索 iTextSharp 安装
/// <summary> /// 图片转PDF /// </summary> /// <param name="jpgfile">图片本地地址</param> /// <param name="pdf">生成的文件路径和文件名</param> /// <returns></returns> public static bool ConvertJPG2PDF(string jpgfile, string pdf) { var document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 25, 25, 25, 25); using (var stream = new FileStream(pdf, FileMode.Create, FileAccess.Write, FileShare.None)) {
//这里加try catch 是因为这个地方我用的时候会报错 但是不影响使用 try { iTextSharp.text.pdf.PdfWriter.GetInstance(document, stream); } catch (Exception ex) { } document.Open(); using (var imageStream = new FileStream(jpgfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { var image = iTextSharp.text.Image.GetInstance(imageStream); if (image.Height > iTextSharp.text.PageSize.A4.Height - 25) { image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25); } else if (image.Width > iTextSharp.text.PageSize.A4.Width - 25) { image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25); } image.Alignment = iTextSharp.text.Image.ALIGN_MIDDLE; document.Add(image); } document.Close(); } return true; }
本文来自博客园,作者:吃兔子的萝卜7,转载请注明原文链接:https://www.cnblogs.com/kangsir7/p/15740454.html
分类:
网站开发
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· Blazor Hybrid适配到HarmonyOS系统
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· 解决跨域问题的这6种方案,真香!
· 分享4款.NET开源、免费、实用的商城系统
· 一套基于 Material Design 规范实现的 Blazor 和 Razor 通用组件库