public static bool ConvertHtml2Pdf(string text, string pdfPath)
{
Document document = new Document(PageSize.A4);
try
{
PdfWriter.GetInstance(document, new FileStream(pdfPath, FileMode.Create));
document.Open();
var fontName = "楷体";
if (!FontFactory.IsRegistered(fontName))
{
var fontPath = Environment.GetFolderPath(Environment.SpecialFolder.Windows) + @"\Fonts\simkai.ttf";
FontFactory.Register(fontPath);
}
var elements = iTextSharp.tool.xml.XMLWorkerHelper.ParseToElementList(text, @"body {
font-size: 16px;
color: #F00;
font-family: 楷体;
}");
//iTextSharp.text.
foreach (var element in elements)
{
document.Add(element);
}
}
catch (DocumentException de)
{
Console.Error.WriteLine(de.Message);
}
catch (IOException ioe)
{
Console.Error.WriteLine(ioe.Message);
}
document.Close();
return true;
}
以上都是转换成pdf的功能,在转换后,我们可以进一步使用ITextSharp对pdf进行加工,比较常见的添加水印功能。其实就是做一个淡淡的背景透明的图片,然后打开pdf文件,在每一页中画上水印图片即可。
/// <summary>
/// 添加水印
/// </summary>
/// <param name="inputPath">源PDF文件路径</param>
/// <param name="outputPath">加水印后的PDF路径</param>
/// <param name="watermarkPath">水印图片的路径</param>
/// <param name="error"></param>
/// <returns></returns>
public static bool AddWatermark(string inputPath, string outputPath, string watermarkPath, ref string error)
{
try
{
PdfReader pdfReader = new PdfReader(inputPath);
int numberOfPages = pdfReader.NumberOfPages;
FileStream outputStream = new FileStream(outputPath, FileMode.Create);
PdfStamper pdfStamper = new PdfStamper(pdfReader, outputStream);
PdfContentByte waterMarkContent;
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(watermarkPath);
image.SetAbsolutePosition(10, 10);
for (int i = 1; i <= numberOfPages; i++)
{
waterMarkContent = pdfStamper.GetUnderContent(i);
waterMarkContent.AddImage(image);
}
pdfStamper.Close();
pdfReader.Close();
outputStream.Close();
return true;
}
catch (Exception ex)
{
error = ex.StackTrace;
return false;
}
}