/// <summary>
/// 将Txt转换为PDF
/// </summary>
/// <param name="sourcePath"></param>
/// <param name="targetPath"></param>
/// <returns></returns>
public static bool ConvertText2Pdf(string sourcePath, string targetPath)
{
var text = FileHelper.ReadTextFile(sourcePath);
Document document = new Document(PageSize.A4);
try
{
//step 2:创建一个writer用于监听Document以及通过PDF-stream指向一个文件
PdfWriter.GetInstance(document, new FileStream(targetPath, FileMode.Create));
// step 3: 打开document
document.Open();
var f = GetFont();
// step 4: 添加一段话到document中
document.Add(new Paragraph(text, f));
}
catch (Exception ex)
{
return false;
}
finally
{
if (document.IsOpen())
// step 5: 关闭document
document.Close();
}
return true;
}
private static Font GetFont()
{
var fontPath = (string) ConfigurationManager.AppSettings["FontPath"];
if (string.IsNullOrEmpty(fontPath))//没有指定字体就用楷体
{
var fontName = "楷体";
if (!FontFactory.IsRegistered(fontName))
{
fontPath = Environment.GetFolderPath(Environment.SpecialFolder.Windows) + @"\Fonts\simkai.ttf";
FontFactory.Register(fontPath);
}
return FontFactory.GetFont(fontName, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
}
BaseFont bfChinese = BaseFont.CreateFont(fontPath,BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
Font fontChinese = new Font(bfChinese, 16f, Font.NORMAL);
return fontChinese;
}
文档在线预览的实现(3)
内容版权声明:除非注明,否则皆为本站原创文章。
转载注明出处:https://www.heiqu.com/1cb824b97a2b0e0be7dde442d019f8df.html