java 生成PDF文件增加密码

package com.me.test;

import java.awt.*;
import java.io.*;

import com.lowagie.text.*;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfWriter;

/**
 * First iText example: Hello World.
 */
public class HelloWorld {

	/** Path to the resulting PDF file. */

	public static final String RESULT = "c:/hello.pdf";

	public static final String pwd = "123456";

	public static final String result = "c:/Itext/b.gif";

	/**
	 * 
	 * Creates a PDF file: hello.pdf
	 * 
	 * 
	 * 
	 * @param args
	 * 
	 *            no arguments needed
	 */

	public static void main(String[] args) throws DocumentException,

	IOException {

		new HelloWorld().createPdf(RESULT);

	}

	/**
	 * 
	 * Creates a PDF document.
	 * 
	 * 
	 * 
	 * @param filename
	 * 
	 *            the path to the new PDF document
	 * 
	 * @throws DocumentException
	 * 
	 * @throws IOException
	 */

	public void createPdf(String filename) throws DocumentException,

	IOException {

		// 设定文本样式
		Rectangle rec = new Rectangle(PageSize.A4);

		rec.setBackgroundColor(Color.GRAY);

		rec.setBorder(Rectangle.TOP);

		rec.setBorderColor(Color.black);

		rec.setBorderWidth(50);

		// 创建本文
		Document doc = new Document(rec, 100, 201, 20, 20);

		// 设定路径
		PdfWriter pdf = PdfWriter.getInstance(doc, new FileOutputStream(HelloWorld.RESULT));

		// 设定布局
		pdf.setViewerPreferences(PdfWriter.PageModeUseThumbs| PdfWriter.PageLayoutTwoColumnLeft | PdfWriter.HideMenubar);

		// 加密
		pdf.setEncryption(pwd.getBytes(), pwd.getBytes(), PdfWriter.ALLOW_COPY| PdfWriter.ALLOW_PRINTING, PdfWriter.STANDARD_ENCRYPTION_40);
		
		// 设置中文
		BaseFont base = null;

		Font fontChinese = null;

		try {

			base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.EMBEDDED);

			fontChinese = new Font(base, 18, Font.BOLD);

		} catch (DocumentException e) {
			e.printStackTrace();

		} catch (IOException e) {

			e.printStackTrace();

		}

		doc.open();

		doc.add(new Paragraph("我是Pro", fontChinese));

		doc.close();

	}
}

package com.me.test;

import java.awt.*;
import java.io.*;

import com.lowagie.text.*;
import com.lowagie.text.Font;
import com.lowagie.text.Image;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.*;

public class PdfConvertor {

	// txt原始文件的路径
	private static final String txtFilePath = "c:/Itext/test.txt";

	// 生成的pdf文件路径
	private static final String pdfFilePath = "c:/Itext/test.pdf";

	// 添加水印图片路径
	private static final String imageFilePath = "c:/Itext/b.gif";

	// 生成临时文件前缀
	private static final String prefix = "tempFile";

	// 所有者密码
	private static final String OWNERPASSWORD = "12345678";

	/**
	 * 
	 * txt文件转换为pdf文件
	 * 
	 * 
	 * 
	 * @param txtFile
	 * 
	 *            txt文件路径
	 * 
	 * @param pdfFile
	 * 
	 *            pdf文件路径
	 * 
	 * @param userPassWord
	 * 
	 *            用户密码
	 * 
	 * @param waterMarkName
	 * 
	 *            水印内容
	 * 
	 * @param permission
	 * 
	 *            操作权限
	 */

	public static void generatePDFWithTxt(String txtFile, String pdfFile,

	String userPassWord, String waterMarkName, int permission) {

		try {

			// 生成临时文件
			File file = File.createTempFile(prefix, ".pdf");

			// 创建pdf文件到临时文件
			if (createPDFFile(txtFile, file)) {

				// 增加水印和加密
				waterMark(file.getPath(), pdfFile, userPassWord, OWNERPASSWORD,

				waterMarkName, permission);

			}

		} catch (Exception e) {

			e.printStackTrace();

		}

	}

	/**
	 * 
	 * 创建PDF文档
	 * 
	 * 
	 * 
	 * @param txtFilePath
	 * 
	 *            txt文件路径(源文件)
	 * 
	 * @param pdfFilePath
	 * 
	 *            pdf文件路径(新文件)
	 */

	private static boolean createPDFFile(String txtFilePath, File file) {

		// 设置纸张
		Rectangle rect = new Rectangle(PageSize.A4);

		// 设置页码
		HeaderFooter footer = new HeaderFooter(new Phrase("页码:",

		setChineseFont()), true);

		footer.setBorder(Rectangle.NO_BORDER);

		// step1
		Document doc = new Document(rect, 50, 50, 50, 50);

		doc.setFooter(footer);

		try {

			FileReader fileRead = new FileReader(txtFilePath);

			BufferedReader read = new BufferedReader(fileRead);

			// 设置pdf文件生成路径 step2
			PdfWriter.getInstance(doc, new FileOutputStream(file));

			// 打开pdf文件 step3
			doc.open();

			// 实例化Paragraph 获取写入pdf文件的内容,调用支持中文的方法. step4
			while (read.ready()) {

				// 添加内容到pdf(这里将会按照txt文件的原始样式输出)
				doc.add(new Paragraph(read.readLine(), PdfConvertor.setChineseFont()));

			}

			// 关闭pdf文件 step5
			doc.close();

			return true;

		} catch (Exception e) {

			e.printStackTrace();

			return false;

		}

	}

	/**
	 * 
	 * 在pdf文件中添加水印
	 * 
	 * 
	 * 
	 * @param inputFile
	 * 
	 *            原始文件
	 * 
	 * @param outputFile
	 * 
	 *            水印输出文件
	 * 
	 * @param waterMarkName
	 * 
	 *            水印名字
	 */

	private static void waterMark(String inputFile, String outputFile,

	String userPassWord, String ownerPassWord, String waterMarkName,

	int permission) {

		try {

			PdfReader reader = new PdfReader(inputFile);

			PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(

			outputFile));

			// 设置密码
			stamper.setEncryption(userPassWord.getBytes(), ownerPassWord.getBytes(), permission, false);

			BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);

			PdfContentByte under;

			int total = reader.getNumberOfPages() + 1;

			Image image = Image.getInstance(imageFilePath);

			image.setAbsolutePosition(200, 400);

			int j = waterMarkName.length();

			char c = 0;

			int rise = 0;

			for (int i = 1; i < total; i++) {

				rise = 500;

				under = stamper.getUnderContent(i);

				// 添加图片
				under.addImage(image);

				under.beginText();

				under.setColorFill(Color.CYAN);

				under.setFontAndSize(base, 30);

				// 设置水印文字字体倾斜 开始
				if (j >= 15) {

					under.setTextMatrix(200, 120);

					for (int k = 0; k < j; k++) {

						under.setTextRise(rise);

						c = waterMarkName.charAt(k);

						under.showText(c + "");

						rise -= 20;

					}

				} else {

					under.setTextMatrix(180, 100);

					for (int k = 0; k < j; k++) {

						under.setTextRise(rise);

						c = waterMarkName.charAt(k);

						under.showText(c + "");

						rise -= 18;

					}

				}

				// 字体设置结束
				under.endText();

				// 画一个圆
				// under.ellipse(250, 450, 350, 550);

				// under.setLineWidth(1f);

				// under.stroke();

			}

			stamper.close();

		} catch (Exception e) {

			e.printStackTrace();

		}

	}

	/**
	 * 
	 * 设置中文
	 * 
	 * 
	 * 
	 * @return Font
	 */

	private static Font setChineseFont() {

		BaseFont base = null;

		Font fontChinese = null;

		try {

			base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",

			BaseFont.EMBEDDED);

			fontChinese = new Font(base, 12, Font.NORMAL);

		} catch (DocumentException e) {

			e.printStackTrace();

		} catch (IOException e) {

			e.printStackTrace();

		}

		return fontChinese;

	}

	public static void main(String[] args) {

		generatePDFWithTxt(txtFilePath, pdfFilePath, OWNERPASSWORD, "allone",16);
	}
}


import java.io.FileOutputStream;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;
/**
 * iText学习笔记:HelloWorld
 * 
 * @author 老紫竹(laozizhu.com)
 */
public class HelloWorld {
  public static void main(String[] args) throws Exception, DocumentException {
    // 新建一个文档,默认是A4纸的大小,4个边框为36
    Document document = new Document();
    // 将文档输出,我们写到文件里面
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("HelloWorld.pdf"));
    writer.setEncryption("Hello".getBytes(), "World".getBytes(), PdfWriter.ALLOW_COPY
        | PdfWriter.ALLOW_PRINTING, PdfWriter.STANDARD_ENCRYPTION_128);
    document.addTitle("Hello World example");
    document.addAuthor("老紫竹");
    document.addSubject("This example explains how to add metadata.");
    document.addKeywords("iText, Hello World, step 3, metadata");
    document.addCreator("My program using iText");
    // 打开文档
    document.open();
    // 写入数据
    document.add(new Paragraph("Hello World"));
    BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
    Font FontChinese = new Font(bfChinese, 12, Font.NORMAL);
    document.add(new Paragraph("老紫竹祝大家新年好!", FontChinese));
    // 关闭文档
    document.close();
  }
}






转自:http://www.xuebuyuan.com/1966318.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java 可以通过 Tableau 的 REST API 连接 Tableau Server 或 Tableau Online,并生成 PDF 报表。具体实现步骤如下: 1. 获取 Tableau Server 的 REST API 首先,需要获取 Tableau Server 的 REST API,可以在 Tableau Server 管理页面中找到。获取 REST API 后,需要将其保存在配置文件中,以便在 Java 代码中使用。 2. 创建 Java 项目 使用开发工具(如 Eclipse 或 IntelliJ IDEA)创建一个 Java 项目,并在项目中导入 Tableau 的 Java SDK。 3. 连接 Tableau Server 在 Java 代码中,需要使用 Tableau 的 Java SDK 连接 Tableau Server 或 Tableau Online。示例代码如下: ``` TableauCredentials tableauCredentials = new TableauCredentials("https://<YOUR_TABLEAU_SERVER>", "<USERNAME>", "<PASSWORD>", "<SITE_NAME>"); TableauServerConnection serverConnection = new TableauServerConnection(tableauCredentials); serverConnection.connect(); ``` 其中,<YOUR_TABLEAU_SERVER> 是 Tableau Server 的地址,<USERNAME> 和 <PASSWORD> 是登录 Tableau Server 的用户名和密码,<SITE_NAME> 是 Tableau Server 的站点名称。 4. 获取 Workbook 获取 Workbook 可以使用 Tableau 的 Java SDK 中的 WorkbookService。示例代码如下: ``` WorkbookService wbService = new WorkbookService(serverConnection); Workbook workbook = wbService.getByName("<WORKBOOK_NAME>", "<PROJECT_NAME>"); ``` 其中,<WORKBOOK_NAME> 是要生成 PDF 的 Workbook 的名称,<PROJECT_NAME> 是 Workbook 所在的项目名称。 5. 设置 PDF 输出选项 使用 Tableau 的 Java SDK 中的 PdfRequestOptions 类,可以设置 PDF 输出选项,如 PDF 的大小、方向、页边距等。示例代码如下: ``` PdfRequestOptions pdfRequestOptions = new PdfRequestOptions(); pdfRequestOptions.setPageSize(PdfRequestOptions.PageSize.LETTER); pdfRequestOptions.setOrientation(PdfRequestOptions.Orientation.PORTRAIT); pdfRequestOptions.setPageMargins(new PdfRequestOptions.PageMargins(0.25, 0.25, 0.25, 0.25)); ``` 6. 生成 PDF 使用 Tableau 的 Java SDK 中的 PdfService 和 PdfRequestOptions,可以生成 PDF 报表。示例代码如下: ``` PdfService pdfService = new PdfService(serverConnection); InputStream pdfStream = pdfService.generatePdf(workbook, pdfRequestOptions); ``` 7. 保存 PDF生成PDF 内容保存为文件,示例代码如下: ``` OutputStream outputStream = new FileOutputStream(new File("<PDF_FILE_PATH>")); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = pdfStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.close(); pdfStream.close(); ``` 其中,<PDF_FILE_PATH> 是保存 PDF 文件的路径。 以上就是使用 Java 连接 Tableau Server 或 Tableau Online,并生成 PDF 报表的步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值