如何保护pdf文件密码? [英] How to make pdf file password protected?

查看:104
本文介绍了如何保护pdf文件密码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要保护pdf文件密码。我只是为了相同而找到一个很好的解决方案。它工作正常但是在使用下面给出的代码保护pdf之后,它消除了我的pdf中已经存在的所有数据。

I want to make pdf file password protected. I just goolge it for the same and find a good solution given below. It's working fine But it wipe out all the data which is already there in my pdf after i secure pdf using below given code.

此代码使用的jar文件是:

Used jar files for this code are:

itextpdf-5.2.1.jar

itextpdf-5.2.1.jar

bcmail-jdk16-1.46.jar

bcmail-jdk16-1.46.jar

bcprov-jdk16-1.46.jar

bcprov-jdk16-1.46.jar

bctsp-jdk16-1.46.jar

bctsp-jdk16-1.46.jar

保护PDF的代码:

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Secure_file {
    private static String USER_PASSWORD = "password";
    private static String OWNER_PASSWORD = "secured";
    public static void main(String[] args) throws IOException {
        Document document = new Document();
        try {
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("E:\\sample.pdf"));
            writer.setEncryption(USER_PASSWORD.getBytes(),OWNER_PASSWORD.getBytes(), PdfWriter.ALLOW_PRINTING,PdfWriter.ENCRYPTION_AES_128);
            document.open();
            document.add(new Paragraph("This is Password Protected PDF document."));
            document.close();
            writer.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

我需要做出哪些改变在这个程序中?

what changes i need to made in this program ?

推荐答案

如果你查找 iText in Action关键字你会发现加密指向示例part3.chapter12。 EncryptionPdf 。该示例的方法 createPdf 基本上等同于您的代码,但方法 encryptPdf 是您想要的:

If you look up the iText in Action keywords you'll find encryption pointing to the sample part3.chapter12.EncryptionPdf. That sample's method createPdf essentially is equivalent to your code but the method encryptPdf is what you want:

/** User password. */
public static byte[] USER = "Hello".getBytes();
/** Owner password. */
public static byte[] OWNER = "World".getBytes();

...

public void encryptPdf(String src, String dest) throws IOException, DocumentException {
    PdfReader reader = new PdfReader(src);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
    stamper.setEncryption(USER, OWNER,
        PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128 | PdfWriter.DO_NOT_ENCRYPT_METADATA);
    stamper.close();
    reader.close();
}

这篇关于如何保护pdf文件密码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆