我正在使用以下代码在 mvc 中使用 itext 和 razorpdf 生产者生成 pdf
@model myModel.Models.Examform
@{
Layout = null;
}
<itext creationdate="@DateTime.Now.ToString()" producer="RazorPDF">
Hello
</text>
这段代码工作正常。我想在生成的 pdf 中添加水印。我知道如何添加图像。我需要一个在背景中显示的水印。
我正在使用以下代码在 mvc 中使用 itext 和 razorpdf 生产者生成 pdf
@model myModel.Models.Examform
@{
Layout = null;
}
<itext creationdate="@DateTime.Now.ToString()" producer="RazorPDF">
Hello
</text>
这段代码工作正常。我想在生成的 pdf 中添加水印。我知道如何添加图像。我需要一个在背景中显示的水印。
这几乎是完全相同的问题
ItextSharp - RazorPdf 将图像放在 Pdf 上
所以使用那里的答案应该适合你:
<image url="@Context.Server.MapPath("~/Images/sampleImage.png")" />
编辑:要在图像上叠加文本,您需要修改 CSS 和 HTML。
http://www.the-art-of-web.com/css/textoverimage/
您可能需要将 CSS 内联。
这是我所做的。代码进入控制器。
[HttpPost]
public FileStreamResult Certificate(MyModel model)
{
Stream fileStream = GeneratePDF(model);
HttpContext.Response.AddHeader("content-disposition", "inline; filename=Certificate.pdf");
var fileStreamResult = new FileStreamResult(fileStream, "application/pdf");
return fileStreamResult;
}
public Stream GeneratePDF(HomeViewModel model)
{
var rect = new Rectangle(288f, 144f);
var doc = new Document(rect, 0, 0, 0, 0);
BaseFont bfArialNarrow = BaseFont.CreateFont(Server.MapPath("../Content/fonts/ARIALN.ttf"), BaseFont.CP1252, BaseFont.EMBEDDED);
//Full Background Image (Includes watermark)
Image fullBackground = null;
fullBackground = Image.GetInstance(Server.MapPath("../Content/images/Certificate/Cert1.jpg"));
doc.SetPageSize(PageSize.LETTER.Rotate());
MemoryStream memoryStream = new MemoryStream();
PdfWriter pdfWriter = PdfWriter.GetInstance(doc, memoryStream);
doc.Open();
//Full Background Image
fullBackground.Alignment = Image.UNDERLYING | Image.ALIGN_CENTER | Image.ALIGN_MIDDLE;
doc.Add(fullBackground);
Font myFont = new Font(bfArialNarrow, 57);
var myParagraph = new Paragraph("Some text here.", myFont);
doc.Add(myParagraph);
pdfWriter.CloseStream = false;
doc.Close();
memoryStream.Position = 0;
return memoryStream;
}
我认为通过标记是不可能的。
如果您查看 RazorPDF 源代码中的 PdfView.cs,它使用 iTextshapt 中的 XmlParser 或 HtmlParser 来呈现 pdf。
https://github.com/RazorAnt/RazorPDF/blob/master/RazorPDF/PdfView.cs
这两个类中对标记的支持是有限的。你只能做他们已经实施的事情。
另一种方法是使用 iTextsharp 通过代码创建 pdf。