我想打印出带有水印的tiff图像。所以,首先我将tiff图像转换为pdf并添加水印以生成pdf.But水印不会出现在最终的pdf中。是否有任何建议打印出带有水印的tiff图像。任何帮助将不胜感激。这是我的代码。
public class TiffToPdf {
private static int TEXT_TILT_ANGLE = 25;
private static Color MEDIUM_GRAY = new Color(242,17,72);
private static int PRIMARY_FONT_SIZE = 50;
private static String tif = "C:/Sample.tif";
private static String pdf = "C:/Sample.pdf";
private static String watermarkpdf = "C:/Watermark.pdf"
public static void main(String[] args) throws Exception {
convert(tif, pdf);
File watermark = new File(watermarkpdf);
OutputStream outputStream = new FileOutputStream(watermark);
addWaterMark(pdf, outputStream, "This is Sample WaterMark");
}
public static File convert(String tif, String pdf) {
File pdfFile = null;
String imgeFilename = tif;
Document document = new Document();
try {
PdfWriter writer = PdfWriter.getInstance(
document,
new FileOutputStream(pdf));
writer.setStrictImageSequence(true);
Image image;
document.open();
RandomAccessFileOrArray ra = new RandomAccessFileOrArray(imgeFilename);
int pagesTif = TiffImage.getNumberOfPages(ra);
for (int i = 1; i <= pagesTif; i++) {
image = TiffImage.getTiffImage(ra, i);
image.scaleAbsolute(PageSize.A4.getWidth(), PageSize.A4.getHeight());
document.setMargins(0, 0, 0, 0);
document.newPage();
document.add(image);
}
pdfFile = new File(pdf);
document.close();
} catch (Exception ex) {
//do nothing
}
return pdfFile;
}
public static void addWaterMark(String pdfFile,OutputStream outputStream, String watermark) throws Exception{
PdfReader reader = new PdfReader(pdfFile);
int numPages = reader.getNumberOfPages();
// Create a stamper that will copy the document to the output
// stream.
PdfStamper stamp = new PdfStamper(reader, outputStream);
int page=1;
BaseFont baseFont =
BaseFont.createFont(BaseFont.HELVETICA_BOLDOBLIQUE,
BaseFont.WINANSI, BaseFont.EMBEDDED);
float width;
float height;
while (page <= numPages) {
PdfContentByte cb = stamp.getOverContent(page);
height = reader.getPageSizeWithRotation(page).getHeight() / 2;
width = reader.getPageSizeWithRotation(page).getWidth() / 2;
cb = stamp.getUnderContent(page);
cb.saveState();
cb.setColorFill(MEDIUM_GRAY);
// Primary Text
cb.beginText();
cb.setFontAndSize(baseFont, PRIMARY_FONT_SIZE);
cb.showTextAligned(Element.ALIGN_CENTER, watermark, width,
height, TEXT_TILT_ANGLE);
cb.endText();
cb.restoreState();
page++;
}
stamp.close();
}
}
答案 0 :(得分:2)
您的代码有很多问题。例如:你说水印没有出现在你的最终PDF中,但是如果你仔细观察,你会发现确实添加了水印,但是它被不透明的图像所覆盖(TIFF你在之前的一段时间内添加了。)
看看你的代码。首先,将cb
定义为覆盖图像的图层:
PdfContentByte cb = stamp.getOverContent(page);
但在该行之后几乎立即重新定义cb
作为现有图像下的图层:
cb = stamp.getUnderContent(page);
删除此行,您的水印就会出现。
您没有帮助客户,因为:
addWatermark()
方法假设坐标系的来源为(0, 0)
且情况并非如此,因此如果您的客户开始将您的方法用于其他PDF,则可能会添加页面可见区域外的水印。总而言之,您的代码不适合生产。我的建议是重写它并使用最新的iText版本。