
具体是这样的,我们现在在开发一个项目,其中有个功能是将用户填写的报表在线生成pdf下载,是通过流直接输出到用户的电脑里,服务器上不会存在生成的pdf文件,但是现在有一个问题,因为pdf文件页数是不确定的,所以在每一页加水印现在无法实现,请问怎样弄才能实现这一功能?我之前的思路是这样的,在生成pdf的java代码最后加个循环,通过得到document的页数然后用pdfContentByte在每一页加水印,但是我没找到可以定位到第几页的方法。部分代码:Javacoderesponse.setContentType(\"text/htmlcharset=GBK\")response.setContentType(\"application/pdf\")response.setHeader(\"Content-Disposition
maven配置iText的jar,主要不是所有私服都有iText的jar,maven仓库没有的,可以去https://mvnrepository.com/artifact/com.itextpdf/itextpdf/5.5.12 这里下载
同样先写个工具类,这里是加文字水印和图片水印的
【拓展功能】
ok,这只是基本功能,然后要对其进行拓展
业务场景:要在上传的pdf文件自动加上二维码水印,用户可以扫描二维码获取对应数据
首先二维码里面其实也就是一些数据,比如一个链接,或者一堆文字等等,这里可以通过Google开源的zxing库来事项生成二维码图片,然后附加到图片,形成水印
maven配置zxing对应jar:
写个工具类用于生成二维码图片:
对于上传的文件,我们怎么知道类型?如果用Spring提供的MultipartFile,这里可以获取ContentType来判断,这里只提供思路
有了工具类之后,我们需要获取文件上传的inputStream
public class WaterMark{
static string strPath = @"C:\Users\Administrator\Desktop\Test\TEST\ConsoleApplication1\bin\Debug\pic\"
public static void CreateWaterMark()
{
try
{
//////参数说明
//inputPath 需要增加水印的pdf文件位置
//outputPath 增加水印后,新生成的pdf文件位置
//watermarkimagepath 水印图片的位置
///////////////
string inputPath = @"C:\Users\Administrator\Desktop\Test\TEST\TEMP_PDF\Chap0605.pdf"
string outputPath = @"C:\Users\Administrator\Desktop\Test\TEST\TEMP_PDF\Chap0605_new.pdf"
string watermarkPath = strPath + "logo.png"
PdfReader pdfReader = new PdfReader(inputPath)
int numberOfPages = pdfReader.NumberOfPages
FileStream outputStream = new FileStream(outputPath, FileMode.Create)
PdfStamper pdfStamper = new PdfStamper(pdfReader, outputStream)
PdfContentByte waterMarkContent
string watermarkimagepath = watermarkPath
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(watermarkimagepath)
image.GrayFill = 100
image.RotationDegrees = -45
iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1)
float width = psize.Width
float height = psize.Height
float left = width / 2 - image.Width + 80
float top = height / 2 - image.Height
image.SetAbsolutePosition(left, top)
for (int i = 1i <= numberOfPagesi++)
{
//waterMarkContent = pdfStamper.GetUnderContent(i)
waterMarkContent = pdfStamper.GetOverContent(i)
PdfGState gs = new PdfGState()
gs.FillOpacity = 0.3f
waterMarkContent.SetGState(gs)
waterMarkContent.AddImage(image)
}
pdfStamper.Close()
pdfReader.Close()
}
catch (Exception ex)
{
// WriteLog.Log(ex.ToString())
throw ex
}
}
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)