Perl: Protection of PDF File with a Password - by Eun Bae Kim (08/26/2018)
 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
  
use strict;
use CAM::PDF;
use LWP::Simple;


my $sUrl = "http://itanimal.ipdisk.co.kr/web_laboratory/research_perl_data/example_doc.pdf";
my $sDownFolder = "Download_PDF";
system("mkdir ".$sDownFolder);

print "--------------------------------------------\n";
my $sLocalFile = $sDownFolder."/".funcFileNameFromPath($sUrl);
my $oRespond = getstore($sUrl, $sLocalFile);    # If a url is not correct, no exception occurs.
if (is_error($oRespond)) {
	print "    Downloading failed: ".$sUrl."\n";
	print "    Error Message: ".$oRespond."\n";
}


sub funcFileNameFromPath {
	my $sFilePath = shift;
	my $sRevPath = reverse($sFilePath);
	my $sFileName = "";

	if ($sRevPath=~/\//){
		$sFileName = $`;
		$sFileName = reverse($sFileName);
	} else {
		$sFileName = $sFilePath;
	}
	return $sFileName;
}


# Protect your pdf file with a password
print "--------------------------------------------\n";
my $sPassword = "abcd1234";
my $sNewPdf = substr($sLocalFile, 0, -4)."_Protected.pdf";
print "Original PDF: ".$sLocalFile."\n";
print "New PDF:      ".$sNewPdf."\n";
print "Password:     ".$sPassword."\n";
funcPdfPass($sLocalFile, $sNewPdf, $sPassword);

sub funcPdfPass () {
	my $sTargetPdf	= shift;
	my $sSavePdf	= shift;
	my $sPassword	= shift;

	print $sTargetPdf."\t".$sSavePdf."\t".$sPassword."\n";


	my $oPdf = CAM::PDF->new($sTargetPdf) or die;

	if ($oPdf) {
		print "Processing: TRUE!!\n";
	} else {
		print "Processing: FALSE!!\n";
	}
	my @oPrefs = $oPdf->getPrefs();
	$oPrefs[$CAM::PDF::PREF_OPASS] = $sPassword;
	$oPrefs[$CAM::PDF::PREF_UPASS] = $sPassword;
	$oPdf->setPrefs(@oPrefs);
	$oPdf->cleanoutput($sSavePdf) or die;
}