public void pdfViewPage() { HttpServletResponse response = getResponse(); try { OutputStream os = response.getOutputStream(); response.setContentType("application/pdf"); Rectangle tRectangle = new Rectangle(PageSize.A4); Document document = new Document(tRectangle); PdfWriter writer= PdfWriter.getInstance(document, os); writer.setPageEmpty(false); document.open(); document.add(new Paragraph("add new paragraph")); PdfContentByte pdfCB = writer.getDirectContentUnder(); FontMapper fm = new AsianFontMapper(AsianFontMapper.ChineseSimplifiedFont, AsianFontMapper.ChineseSimplifiedEncoding_H); Method getPdfDocument = writer.getClass().getDeclaredMethod("getPdfDocument"); getPdfDocument.setAccessible(true); PdfDocument pdfD = (PdfDocument) getPdfDocument.invoke(writer); Field getHeight = pdfD.getClass().getDeclaredField("currentHeight"); getHeight.setAccessible(true); float currentHeight = (float)getHeight.get(pdfD); //至此,获得当前的操作高度,并且画了个圈,随后再在这个圈里写入文字。 PdfGraphics2D pdfG = new PdfGraphics2D(pdfCB, tRectangle.getWidth(),tRectangle.getHeight(), fm); pdfG.setPaint(new Color(188, 111, 201)); pdfG.fillOval(143, (int)currentHeight, 100,100 ); pdfG.dispose(); document.add(new Paragraph("text line over graphics")); document.close(); os.flush(); os.close(); } catch (Exception ex) { ex.printStackTrace(); } renderNull(); return; }
项目中需要在特定位置呈现图片等内容,需要用到当前位置的高度,自己又没查到直接获取PdfWriter直接获取currentHeight的方法,知道的朋友给指点一下哈