Convert PostScript to PDF from D lang calling GhostScript ps2pdf.
I’m learning D. I know, I am a program language hopper. This code provides working examples of getopts, concurrency, and a process call to convert PostScript to PDF using GhostScript in the D language.
D
x
107
107
1
import std.getopt;
2
import std.stdio;
3
import std.file;
4
import std.path;
5
import std.datetime;
6
import std.algorithm;
7
import std.array;
8
import std.conv;
9
import std.string;
10
import std.process;
11
import std.concurrency;
12
13
string[] listdir(string path)
14
{
15
return dirEntries(path, "*.ps", SpanMode.shallow)
16
.filter!(f => f.isFile)
17
.map!(f => buildPath(path, f.name))
18
.array;
19
}
20
21
void rip(string path, bool v=false)
22
{
23
//ps2pdf filename.ps filename.pdf
24
string outpath = path.replace(".ps", ".pdf");
25
if (v == true) {
26
writefln("OUT: %s", outpath);
27
}
28
auto logFile = File("errors.log", "w");
29
auto pid = spawnProcess(["/usr/bin/ps2pdf", path, outpath],
30
std.stdio.stdin,
31
std.stdio.stdout,
32
logFile);
33
wait(pid);
34
}
35
36
void main(string[] arguments)
37
{
38
39
// Get opts
40
auto base_path = "/home/username/Documents/postscript";
41
bool render = false;
42
bool count = false;
43
bool verbose = false;
44
45
getopt(
46
arguments,
47
"p|path", &base_path,
48
"r|render", &render,
49
"c|count", &count,
50
"v|verbose", &verbose
51
);
52
53
// $./psmerge -p /home/username/Documents/postscript -r -c -v
54
StopWatch sw;
55
sw.start();
56
57
int totalDocs = 0;
58
int totalPages = 0;
59
if (base_path.exists) {
60
61
string[] psfiles = listdir(base_path);
62
foreach(ps; psfiles){
63
64
if (render == true) {
65
66
auto tid = spawn(&rip, ps, verbose);
67
68
if (verbose == true){
69
writeln(tid, " \nIN: ", ps);
70
}
71
}
72
73
totalDocs++;
74
75
// Count pages.
76
if (count == true) {
77
// Read file.
78
File fileHandle = File(ps, "r");
79
80
while (!fileHandle.eof())
81
{
82
string line = fileHandle.readln();
83
if ( canFind(line, "(atend)") ) {
84
continue;
85
}
86
if ( canFind(line, "%%Pages: ") ) {
87
88
string[] s = line.split(":");
89
auto pgNum = strip(s[1].replace("\r\n",""));
90
91
if (verbose == true){
92
writeln("Pages: ", pgNum);
93
}
94
95
auto pgCount = to!long(pgNum);
96
totalPages += pgCount;
97
}
98
}
99
}
100
}
101
writefln("Total Docs: %s", totalDocs);
102
writefln("Total Pages: %s", totalPages);
103
104
sw.stop();
105
writefln("Elapsed: %f seconds", sw.peek().usecs / 1_000_000.0);
106
}
107
}