Merge branch 'master' of xbib.org:joerg/graphics

This commit is contained in:
Jörg Prante 2021-03-18 21:24:20 +01:00
commit b66887385c
40 changed files with 209 additions and 398 deletions

View file

@ -25,6 +25,9 @@ ext {
subprojects { subprojects {
apply plugin: 'java-library' apply plugin: 'java-library'
repositories {
mavenCentral()
}
apply from: rootProject.file('gradle/ide/idea.gradle') apply from: rootProject.file('gradle/ide/idea.gradle')
apply from: rootProject.file('gradle/compile/java.gradle') apply from: rootProject.file('gradle/compile/java.gradle')
apply from: rootProject.file('gradle/test/junit5.gradle') apply from: rootProject.file('gradle/test/junit5.gradle')

View file

@ -1,6 +1,6 @@
group = org.xbib.graphics group = org.xbib.graphics
name = graphics name = graphics
version = 4.0.1 version = 4.0.2
gradle.wrapper.version = 6.6.1 gradle.wrapper.version = 6.6.1
pdfbox.version = 2.0.22 pdfbox.version = 2.0.22

View file

@ -36,6 +36,7 @@ artifacts {
} }
tasks.withType(JavaCompile) { tasks.withType(JavaCompile) {
options.encoding('UTF-8')
options.compilerArgs << '-Xlint:all' options.compilerArgs << '-Xlint:all'
} }

View file

@ -54,6 +54,7 @@ if (project.hasProperty("signing.keyId")) {
} }
} }
if (project.hasProperty('ossrhUsername')) {
nexusPublishing { nexusPublishing {
repositories { repositories {
sonatype { sonatype {
@ -64,3 +65,4 @@ nexusPublishing {
} }
clientTimeout = Duration.ofSeconds(600) clientTimeout = Duration.ofSeconds(600)
} }
}

View file

@ -22,7 +22,7 @@ import java.nio.file.Files;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.Locale; import java.util.Locale;
public class SvgRendererTest { public class SVGRendererTest {
private Locale originalDefaultLocale; private Locale originalDefaultLocale;

View file

@ -26,7 +26,6 @@ clipsave
gsave gsave
0.0 0.0 0.0 rgb 0.0 0.0 0.0 rgb
1.0 setlinewidth 0 setlinejoin 0 setlinecap [] 0.0 setdash 1.0 setlinewidth 0 setlinejoin 0 setlinecap [] 0.0 setdash
/DejaVuSansLat /DejaVuSans latinize /DejaVuSansLat 12.0 selectfont
1.0 1.0 1.0 rgb 1.0 1.0 1.0 rgb
newpath 0.0 0.0 128.0 60.0 rect Z fill newpath 0.0 0.0 128.0 60.0 rect Z fill
0.0 0.0 0.0 rgb 0.0 0.0 0.0 rgb

View file

@ -32,15 +32,11 @@ q
/Fnt0 12.0 Tf /Fnt0 12.0 Tf
q q
0 J 0 J
/Fnt0 12.0 Tf
0 0 m 128 0 l 128 60 l 0 60 l 0 0 l h f 0 0 m 128 0 l 128 60 l 0 60 l 0 0 l h f
Q Q
q q
0 0 0 rg 0 0 0 RG 0 0 0 rg 0 0 0 RG
0 J 0 J
/Fnt0 12.0 Tf
5 5 m 6 5 l 6 45 l 5 45 l h f 5 5 m 6 5 l 6 45 l 5 45 l h f
7 5 m 8 5 l 8 45 l 7 45 l h f 7 5 m 8 5 l 8 45 l 7 45 l h f
9 5 m 13 5 l 13 45 l 9 45 l h f 9 5 m 13 5 l 13 45 l 9 45 l h f
@ -93,7 +89,7 @@ Q
endstream endstream
endobj endobj
5 0 obj 5 0 obj
1684 1654
endobj endobj
6 0 obj 6 0 obj
<< <<
@ -121,13 +117,13 @@ xref
0000000058 00000 n 0000000058 00000 n
0000000115 00000 n 0000000115 00000 n
0000000248 00000 n 0000000248 00000 n
0000001984 00000 n 0000001954 00000 n
0000002004 00000 n 0000001974 00000 n
trailer trailer
<< <<
/Size 7 /Size 7
/Root 1 0 R /Root 1 0 R
>> >>
startxref startxref
2267 2237
%%EOF %%EOF

View file

@ -26,7 +26,6 @@ clipsave
gsave gsave
0.0 0.0 0.0 rgb 0.0 0.0 0.0 rgb
1.0 setlinewidth 0 setlinejoin 0 setlinecap [] 0.0 setdash 1.0 setlinewidth 0 setlinejoin 0 setlinecap [] 0.0 setdash
/DejaVuSansLat /DejaVuSans latinize /DejaVuSansLat 12.0 selectfont
0.0 1.0 0.0 rgb 0.0 1.0 0.0 rgb
newpath 0.0 0.0 128.0 60.0 rect Z fill newpath 0.0 0.0 128.0 60.0 rect Z fill
1.0 0.0 0.0 rgb 1.0 0.0 0.0 rgb

View file

@ -33,15 +33,11 @@ q
q q
0 1 0 rg 0 1 0 RG 0 1 0 rg 0 1 0 RG
0 J 0 J
/Fnt0 12.0 Tf
0 0 m 128 0 l 128 60 l 0 60 l 0 0 l h f 0 0 m 128 0 l 128 60 l 0 60 l 0 0 l h f
Q Q
q q
1 0 0 rg 1 0 0 RG 1 0 0 rg 1 0 0 RG
0 J 0 J
/Fnt0 12.0 Tf
5 5 m 6 5 l 6 45 l 5 45 l h f 5 5 m 6 5 l 6 45 l 5 45 l h f
7 5 m 8 5 l 8 45 l 7 45 l h f 7 5 m 8 5 l 8 45 l 7 45 l h f
9 5 m 13 5 l 13 45 l 9 45 l h f 9 5 m 13 5 l 13 45 l 9 45 l h f
@ -94,7 +90,7 @@ Q
endstream endstream
endobj endobj
5 0 obj 5 0 obj
1702 1672
endobj endobj
6 0 obj 6 0 obj
<< <<
@ -122,13 +118,13 @@ xref
0000000058 00000 n 0000000058 00000 n
0000000115 00000 n 0000000115 00000 n
0000000248 00000 n 0000000248 00000 n
0000002002 00000 n 0000001972 00000 n
0000002022 00000 n 0000001992 00000 n
trailer trailer
<< <<
/Size 7 /Size 7
/Root 1 0 R /Root 1 0 R
>> >>
startxref startxref
2285 2255
%%EOF %%EOF

View file

@ -26,7 +26,6 @@ clipsave
gsave gsave
0.0 0.0 0.0 rgb 0.0 0.0 0.0 rgb
1.0 setlinewidth 0 setlinejoin 0 setlinecap [] 0.0 setdash 1.0 setlinewidth 0 setlinejoin 0 setlinecap [] 0.0 setdash
/DejaVuSansLat /DejaVuSans latinize /DejaVuSansLat 12.0 selectfont
1.0 1.0 1.0 rgb 1.0 1.0 1.0 rgb
newpath 0.0 0.0 128.0 82.0 rect Z fill newpath 0.0 0.0 128.0 82.0 rect Z fill
0.0 0.0 0.0 rgb 0.0 0.0 0.0 rgb

View file

@ -32,15 +32,11 @@ q
/Fnt0 12.0 Tf /Fnt0 12.0 Tf
q q
0 J 0 J
/Fnt0 12.0 Tf
0 0 m 128 0 l 128 82 l 0 82 l 0 0 l h f 0 0 m 128 0 l 128 82 l 0 82 l 0 0 l h f
Q Q
q q
0 0 0 rg 0 0 0 RG 0 0 0 rg 0 0 0 RG
0 J 0 J
/Fnt0 12.0 Tf
5 5 m 6 5 l 6 45 l 5 45 l h f 5 5 m 6 5 l 6 45 l 5 45 l h f
7 5 m 8 5 l 8 45 l 7 45 l h f 7 5 m 8 5 l 8 45 l 7 45 l h f
9 5 m 13 5 l 13 45 l 9 45 l h f 9 5 m 13 5 l 13 45 l 9 45 l h f
@ -93,7 +89,7 @@ Q
endstream endstream
endobj endobj
5 0 obj 5 0 obj
1688 1658
endobj endobj
6 0 obj 6 0 obj
<< <<
@ -121,13 +117,13 @@ xref
0000000058 00000 n 0000000058 00000 n
0000000115 00000 n 0000000115 00000 n
0000000248 00000 n 0000000248 00000 n
0000001988 00000 n 0000001958 00000 n
0000002008 00000 n 0000001978 00000 n
trailer trailer
<< <<
/Size 7 /Size 7
/Root 1 0 R /Root 1 0 R
>> >>
startxref startxref
2271 2241
%%EOF %%EOF

View file

@ -26,7 +26,6 @@ clipsave
gsave gsave
0.0 0.0 0.0 rgb 0.0 0.0 0.0 rgb
1.0 setlinewidth 0 setlinejoin 0 setlinecap [] 0.0 setdash 1.0 setlinewidth 0 setlinejoin 0 setlinecap [] 0.0 setdash
/DejaVuSansLat /DejaVuSans latinize /DejaVuSansLat 12.0 selectfont
1.0 1.0 1.0 rgb 1.0 1.0 1.0 rgb
newpath 0.0 0.0 256.0 120.0 rect Z fill newpath 0.0 0.0 256.0 120.0 rect Z fill
0.0 0.0 0.0 rgb 0.0 0.0 0.0 rgb

View file

@ -32,15 +32,11 @@ q
/Fnt0 12.0 Tf /Fnt0 12.0 Tf
q q
0 J 0 J
/Fnt0 12.0 Tf
0 0 m 256 0 l 256 120 l 0 120 l 0 0 l h f 0 0 m 256 0 l 256 120 l 0 120 l 0 0 l h f
Q Q
q q
0 0 0 rg 0 0 0 RG 0 0 0 rg 0 0 0 RG
0 J 0 J
/Fnt0 12.0 Tf
10 10 m 12 10 l 12 90 l 10 90 l h f 10 10 m 12 10 l 12 90 l 10 90 l h f
14 10 m 16 10 l 16 90 l 14 90 l h f 14 10 m 16 10 l 16 90 l 14 90 l h f
18 10 m 26 10 l 26 90 l 18 90 l h f 18 10 m 26 10 l 26 90 l 18 90 l h f
@ -93,7 +89,7 @@ Q
endstream endstream
endobj endobj
5 0 obj 5 0 obj
1845 1815
endobj endobj
6 0 obj 6 0 obj
<< <<
@ -121,13 +117,13 @@ xref
0000000058 00000 n 0000000058 00000 n
0000000115 00000 n 0000000115 00000 n
0000000248 00000 n 0000000248 00000 n
0000002145 00000 n 0000002115 00000 n
0000002165 00000 n 0000002135 00000 n
trailer trailer
<< <<
/Size 7 /Size 7
/Root 1 0 R /Root 1 0 R
>> >>
startxref startxref
2428 2398
%%EOF %%EOF

View file

@ -26,7 +26,6 @@ clipsave
gsave gsave
0.0 0.0 0.0 rgb 0.0 0.0 0.0 rgb
1.0 setlinewidth 0 setlinejoin 0 setlinecap [] 0.0 setdash 1.0 setlinewidth 0 setlinejoin 0 setlinecap [] 0.0 setdash
/DejaVuSansLat /DejaVuSans latinize /DejaVuSansLat 12.0 selectfont
1.0 1.0 1.0 rgb 1.0 1.0 1.0 rgb
newpath 0.0 0.0 158.0 90.0 rect Z fill newpath 0.0 0.0 158.0 90.0 rect Z fill
0.0 0.0 0.0 rgb 0.0 0.0 0.0 rgb

View file

@ -32,15 +32,11 @@ q
/Fnt0 12.0 Tf /Fnt0 12.0 Tf
q q
0 J 0 J
/Fnt0 12.0 Tf
0 0 m 158 0 l 158 90 l 0 90 l 0 0 l h f 0 0 m 158 0 l 158 90 l 0 90 l 0 0 l h f
Q Q
q q
0 0 0 rg 0 0 0 RG 0 0 0 rg 0 0 0 RG
0 J 0 J
/Fnt0 12.0 Tf
20 20 m 21 20 l 21 60 l 20 60 l h f 20 20 m 21 20 l 21 60 l 20 60 l h f
22 20 m 23 20 l 23 60 l 22 60 l h f 22 20 m 23 20 l 23 60 l 22 60 l h f
24 20 m 28 20 l 28 60 l 24 60 l h f 24 20 m 28 20 l 28 60 l 24 60 l h f
@ -93,7 +89,7 @@ Q
endstream endstream
endobj endobj
5 0 obj 5 0 obj
1795 1765
endobj endobj
6 0 obj 6 0 obj
<< <<
@ -121,13 +117,13 @@ xref
0000000058 00000 n 0000000058 00000 n
0000000115 00000 n 0000000115 00000 n
0000000247 00000 n 0000000247 00000 n
0000002094 00000 n 0000002064 00000 n
0000002114 00000 n 0000002084 00000 n
trailer trailer
<< <<
/Size 7 /Size 7
/Root 1 0 R /Root 1 0 R
>> >>
startxref startxref
2377 2347
%%EOF %%EOF

View file

@ -26,7 +26,6 @@ clipsave
gsave gsave
0.0 0.0 0.0 rgb 0.0 0.0 0.0 rgb
1.0 setlinewidth 0 setlinejoin 0 setlinecap [] 0.0 setdash 1.0 setlinewidth 0 setlinejoin 0 setlinecap [] 0.0 setdash
/DejaVuSansLat /DejaVuSans latinize /DejaVuSansLat 12.0 selectfont
1.0 1.0 1.0 rgb 1.0 1.0 1.0 rgb
newpath 0.0 0.0 420.0 410.0 rect Z fill newpath 0.0 0.0 420.0 410.0 rect Z fill
0.0 0.0 0.0 rgb 0.0 0.0 0.0 rgb

View file

@ -32,15 +32,11 @@ q
/Fnt0 12.0 Tf /Fnt0 12.0 Tf
q q
0 J 0 J
/Fnt0 12.0 Tf
0 0 m 420 0 l 420 410 l 0 410 l 0 0 l h f 0 0 m 420 0 l 420 410 l 0 410 l 0 0 l h f
Q Q
q q
0 0 0 rg 0 0 0 RG 0 0 0 rg 0 0 0 RG
0 J 0 J
/Fnt0 12.0 Tf
43.45 38.4 m 48.825 35.275 l 48.825 29.025 l 43.45 25.9 l 38.075 29.025 l 38.075 35.275 l h f 43.45 38.4 m 48.825 35.275 l 48.825 29.025 l 43.45 25.9 l 38.075 29.025 l 38.075 35.275 l h f
68.05 38.4 m 73.425 35.275 l 73.425 29.025 l 68.05 25.9 l 62.675 29.025 l 62.675 35.275 l h f 68.05 38.4 m 73.425 35.275 l 73.425 29.025 l 68.05 25.9 l 62.675 29.025 l 62.675 35.275 l h f
92.65 38.4 m 98.025 35.275 l 98.025 29.025 l 92.65 25.9 l 87.275 29.025 l 87.275 35.275 l h f 92.65 38.4 m 98.025 35.275 l 98.025 29.025 l 92.65 25.9 l 87.275 29.025 l 87.275 35.275 l h f
@ -414,41 +410,31 @@ q
Q Q
q q
0 J 0 J
/Fnt0 12.0 Tf
248.64999999999998 203 m 248.64999999999998 227.76997102991106 228.56997102991107 247.85 203.79999999999998 247.85 c 179.0300289700889 247.85 158.95 227.76997102991106 158.95 203 c 158.95 178.2300289700889 179.0300289700889 158.15 203.79999999999998 158.15 c 228.56997102991107 158.15 248.64999999999998 178.2300289700889 248.64999999999998 203 c h f 248.64999999999998 203 m 248.64999999999998 227.76997102991106 228.56997102991107 247.85 203.79999999999998 247.85 c 179.0300289700889 247.85 158.95 227.76997102991106 158.95 203 c 158.95 178.2300289700889 179.0300289700889 158.15 203.79999999999998 158.15 c 228.56997102991107 158.15 248.64999999999998 178.2300289700889 248.64999999999998 203 c h f
Q Q
q q
0 0 0 rg 0 0 0 RG 0 0 0 rg 0 0 0 RG
0 J 0 J
/Fnt0 12.0 Tf
239.3 203 m 239.3 222.60610861899318 223.40610861899316 238.5 203.79999999999998 238.5 c 184.19389138100684 238.5 168.29999999999998 222.60610861899318 168.29999999999998 203 c 168.29999999999998 183.39389138100685 184.19389138100684 167.5 203.79999999999998 167.5 c 223.40610861899316 167.5 239.3 183.39389138100685 239.3 203 c h f 239.3 203 m 239.3 222.60610861899318 223.40610861899316 238.5 203.79999999999998 238.5 c 184.19389138100684 238.5 168.29999999999998 222.60610861899318 168.29999999999998 203 c 168.29999999999998 183.39389138100685 184.19389138100684 167.5 203.79999999999998 167.5 c 223.40610861899316 167.5 239.3 183.39389138100685 239.3 203 c h f
Q Q
q q
0 J 0 J
/Fnt0 12.0 Tf
229.89999999999998 203 m 229.89999999999998 217.41463197058368 218.2146319705837 229.1 203.79999999999998 229.1 c 189.38536802941627 229.1 177.7 217.41463197058368 177.7 203 c 177.7 188.5853680294163 189.38536802941627 176.9 203.79999999999998 176.9 c 218.2146319705837 176.9 229.89999999999998 188.5853680294163 229.89999999999998 203 c h f 229.89999999999998 203 m 229.89999999999998 217.41463197058368 218.2146319705837 229.1 203.79999999999998 229.1 c 189.38536802941627 229.1 177.7 217.41463197058368 177.7 203 c 177.7 188.5853680294163 189.38536802941627 176.9 203.79999999999998 176.9 c 218.2146319705837 176.9 229.89999999999998 188.5853680294163 229.89999999999998 203 c h f
Q Q
q q
0 0 0 rg 0 0 0 RG 0 0 0 rg 0 0 0 RG
0 J 0 J
/Fnt0 12.0 Tf
220.35 203 m 220.35 212.14031260969963 212.94031260969962 219.55 203.79999999999998 219.55 c 194.65968739030035 219.55 187.24999999999997 212.14031260969963 187.24999999999997 203 c 187.24999999999997 193.85968739030037 194.65968739030035 186.45 203.79999999999998 186.45 c 212.94031260969962 186.45 220.35 193.85968739030037 220.35 203 c h f 220.35 203 m 220.35 212.14031260969963 212.94031260969962 219.55 203.79999999999998 219.55 c 194.65968739030035 219.55 187.24999999999997 212.14031260969963 187.24999999999997 203 c 187.24999999999997 193.85968739030037 194.65968739030035 186.45 203.79999999999998 186.45 c 212.94031260969962 186.45 220.35 193.85968739030037 220.35 203 c h f
Q Q
q q
0 J 0 J
/Fnt0 12.0 Tf
210.95 203.00000000000003 m 210.95 206.9488359612902 207.74883596129015 210.15000000000003 203.79999999999998 210.15000000000003 c 199.8511640387098 210.15000000000003 196.64999999999998 206.9488359612902 196.64999999999998 203.00000000000003 c 196.64999999999998 199.05116403870986 199.8511640387098 195.85000000000002 203.79999999999998 195.85000000000002 c 207.74883596129015 195.85000000000002 210.95 199.05116403870986 210.95 203.00000000000003 c h f 210.95 203.00000000000003 m 210.95 206.9488359612902 207.74883596129015 210.15000000000003 203.79999999999998 210.15000000000003 c 199.8511640387098 210.15000000000003 196.64999999999998 206.9488359612902 196.64999999999998 203.00000000000003 c 196.64999999999998 199.05116403870986 199.8511640387098 195.85000000000002 203.79999999999998 195.85000000000002 c 207.74883596129015 195.85000000000002 210.95 199.05116403870986 210.95 203.00000000000003 c h f
Q Q
Q Q
endstream endstream
endobj endobj
5 0 obj 5 0 obj
64455 64350
endobj endobj
6 0 obj 6 0 obj
<< <<
@ -470,13 +456,13 @@ xref
0000000058 00000 n 0000000058 00000 n
0000000115 00000 n 0000000115 00000 n
0000000248 00000 n 0000000248 00000 n
0000064755 00000 n 0000064650 00000 n
0000064776 00000 n 0000064671 00000 n
trailer trailer
<< <<
/Size 7 /Size 7
/Root 1 0 R /Root 1 0 R
>> >>
startxref startxref
64947 64842
%%EOF %%EOF

View file

@ -91,7 +91,7 @@ public class PDFConverter {
this.compatibilityLevel = compatibilityLevel; this.compatibilityLevel = compatibilityLevel;
this.pdfx = pdfx; this.pdfx = pdfx;
this.paperSize = paperSize; this.paperSize = paperSize;
this.tmpPath = Paths.get("/var/tmp/" + this); this.tmpPath = Paths.get(System.getProperty("java.io.tmpdir", "/var/tmp")).resolve(toString());
} }
/** /**

View file

@ -25,6 +25,7 @@ import java.io.OutputStream;
import java.nio.file.FileVisitResult; import java.nio.file.FileVisitResult;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor; import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption; import java.nio.file.StandardCopyOption;
@ -46,26 +47,31 @@ public class PDFRasterizer implements Closeable {
private static final Logger logger = Logger.getLogger(PDFRasterizer.class.getName()); private static final Logger logger = Logger.getLogger(PDFRasterizer.class.getName());
private final String creator; private String creator;
private final String author; private String author;
private final String subject; private String subject;
private final Map<String, ImageReader> imageReaders; private final Map<String, ImageReader> imageReaders;
private final Path tmpPath; private final Path tmpPath;
public PDFRasterizer(String subject) { public PDFRasterizer() {
this("org.xbib.graphics.ghostscript/4.0.1", "Jörg Prante", subject); this.imageReaders = createImageReaders();
this.tmpPath = Paths.get(System.getProperty("java.io.tmpdir", "/var/tmp")).resolve(toString());
} }
public PDFRasterizer(String creator, String author, String subject) { public void setCreator(String creator) {
this.creator = creator; this.creator = creator;
}
public void setAuthor(String author) {
this.author = author; this.author = author;
}
public void setSubject(String subject) {
this.subject = subject; this.subject = subject;
this.imageReaders = createImageReaders();
this.tmpPath = Paths.get("/var/tmp/" + this);
} }
@Override @Override
@ -199,21 +205,33 @@ public class PDFRasterizer implements Closeable {
} }
} }
public synchronized int mergeImagesToPDF(Path sourceDir, Path targetFile) throws IOException { public int mergeImagesToPDF(Path sourceDir, Path targetFile) throws IOException {
logger.info("mergeImagesToPDF: source=" + sourceDir + " target=" + targetFile); return mergeImagesToPDF(sourceDir, targetFile, "**/*");
}
public synchronized int mergeImagesToPDF(Path sourceDir, Path targetFile, String globPattern) throws IOException {
logger.info("mergeImagesToPDF: source=" + sourceDir + " target=" + targetFile + " glob =" + globPattern);
int pagecount = 0; int pagecount = 0;
PathMatcher pathMatcher = sourceDir.getFileSystem().getPathMatcher("glob:" + globPattern);
List<PDDocument> coverPageDocs = new ArrayList<>(); List<PDDocument> coverPageDocs = new ArrayList<>();
try (Stream<Path> files = Files.list(sourceDir); try (Stream<Path> files = Files.list(sourceDir);
PDDocument pdDocument = new PDDocument(MemoryUsageSetting.setupTempFileOnly()); PDDocument pdDocument = new PDDocument(MemoryUsageSetting.setupTempFileOnly());
OutputStream outputStream = new BufferedOutputStream(Files.newOutputStream(targetFile))) { OutputStream outputStream = new BufferedOutputStream(Files.newOutputStream(targetFile))) {
List<Path> entries = files.sorted() List<Path> entries = files.sorted()
.filter(PDFRasterizer::checkForRealFile) .filter(PDFRasterizer::checkForRealFile)
.filter(pathMatcher::matches)
.collect(Collectors.toList()); .collect(Collectors.toList());
pdDocument.getDocumentInformation().setTitle(targetFile.getFileName().toString()); pdDocument.getDocumentInformation().setTitle(targetFile.getFileName().toString());
pdDocument.getDocumentInformation().setCreationDate(Calendar.getInstance()); pdDocument.getDocumentInformation().setCreationDate(Calendar.getInstance());
if (creator != null) {
pdDocument.getDocumentInformation().setCreator(creator); pdDocument.getDocumentInformation().setCreator(creator);
}
if (subject != null) {
pdDocument.getDocumentInformation().setSubject(subject); pdDocument.getDocumentInformation().setSubject(subject);
}
if (author != null) {
pdDocument.getDocumentInformation().setAuthor(author); pdDocument.getDocumentInformation().setAuthor(author);
}
for (Path path : entries) { for (Path path : entries) {
if (path.getFileName().toString().toLowerCase(Locale.ROOT).endsWith(".pdf")) { if (path.getFileName().toString().toLowerCase(Locale.ROOT).endsWith(".pdf")) {
logger.info("found pdf " + path); logger.info("found pdf " + path);
@ -237,7 +255,6 @@ public class PDFRasterizer implements Closeable {
logger.log(Level.WARNING, "skipping image because too large: " + path + " size = " + size); logger.log(Level.WARNING, "skipping image because too large: " + path + " size = " + size);
} else { } else {
BufferedImage bufferedImage = readImage(path); BufferedImage bufferedImage = readImage(path);
if (bufferedImage != null) {
PDPage page = new PDPage(new PDRectangle(bufferedImage.getWidth(), bufferedImage.getHeight())); PDPage page = new PDPage(new PDRectangle(bufferedImage.getWidth(), bufferedImage.getHeight()));
pdDocument.addPage(page); pdDocument.addPage(page);
PDImageXObject pdImageXObject = LosslessFactory.createFromImage(pdDocument, bufferedImage); PDImageXObject pdImageXObject = LosslessFactory.createFromImage(pdDocument, bufferedImage);
@ -253,10 +270,6 @@ public class PDFRasterizer implements Closeable {
throw new IOException("unable to create PDImageXObject from buffered image"); throw new IOException("unable to create PDImageXObject from buffered image");
} }
bufferedImage.flush(); bufferedImage.flush();
} else {
logger.log(Level.WARNING, "unable to read into a buffered image frmo " + path);
throw new IOException("unable to read into a buffered image");
}
} }
} }
} }
@ -424,7 +437,7 @@ public class PDFRasterizer implements Closeable {
imageReader.setInput(imageInputStream); imageReader.setInput(imageInputStream);
ImageReadParam param = imageReader.getDefaultReadParam(); ImageReadParam param = imageReader.getDefaultReadParam();
BufferedImage bufferedImage = imageReader.read(0, param); BufferedImage bufferedImage = imageReader.read(0, param);
logger.log(Level.FINE, "path = " + path + "loaded: width = " + bufferedImage.getWidth() + logger.log(Level.FINE, "path = " + path + " loaded, width = " + bufferedImage.getWidth() +
" height = " + bufferedImage.getHeight() + " height = " + bufferedImage.getHeight() +
" color model = " + bufferedImage.getColorModel()); " color model = " + bufferedImage.getColorModel());
imageInputStream.close(); imageInputStream.close();

View file

@ -22,12 +22,9 @@ public class PDFRasterizerTest {
@Test @Test
public void testPDFCreation() throws IOException { public void testPDFCreation() throws IOException {
String creator = "Xbib PDF";
String author = "Jörg Prante";
String subject = "Test";
Path sourceDir = Paths.get("src/test/resources/org/xbib/graphics/ghostscript/test/images-3656573"); Path sourceDir = Paths.get("src/test/resources/org/xbib/graphics/ghostscript/test/images-3656573");
Path targetFile = Paths.get("build/3656573.pdf"); Path targetFile = Paths.get("build/3656573.pdf");
PDFRasterizer pdfRasterizer = new PDFRasterizer(creator, author, subject); PDFRasterizer pdfRasterizer = new PDFRasterizer();
int pagecount = pdfRasterizer.mergeImagesToPDF(sourceDir, targetFile); int pagecount = pdfRasterizer.mergeImagesToPDF(sourceDir, targetFile);
logger.info("pagecount = " + pagecount); logger.info("pagecount = " + pagecount);
pdfRasterizer.close(); pdfRasterizer.close();
@ -35,12 +32,9 @@ public class PDFRasterizerTest {
@Test @Test
public void testPDFColorImage() throws IOException { public void testPDFColorImage() throws IOException {
String creator = "Xbib PDF";
String author = "Jörg Prante";
String subject = "Test";
Path sourceDir = Paths.get("src/test/resources/org/xbib/graphics/ghostscript/test/images"); Path sourceDir = Paths.get("src/test/resources/org/xbib/graphics/ghostscript/test/images");
Path targetFile = Paths.get("build/color.pdf"); Path targetFile = Paths.get("build/color.pdf");
PDFRasterizer pdfRasterizer = new PDFRasterizer(creator, author, subject); PDFRasterizer pdfRasterizer = new PDFRasterizer();
int pagecount = pdfRasterizer.mergeImagesToPDF(sourceDir, targetFile); int pagecount = pdfRasterizer.mergeImagesToPDF(sourceDir, targetFile);
logger.info("pagecount = " + pagecount); logger.info("pagecount = " + pagecount);
pdfRasterizer.close(); pdfRasterizer.close();
@ -52,7 +46,7 @@ public class PDFRasterizerTest {
Path target = Paths.get("build/20200024360-new.pdf"); Path target = Paths.get("build/20200024360-new.pdf");
Path tmp = Files.createTempDirectory("graphics-test"); Path tmp = Files.createTempDirectory("graphics-test");
try { try {
PDFRasterizer pdfRasterizer = new PDFRasterizer("xbib", "Jörg Prante", "Test"); PDFRasterizer pdfRasterizer = new PDFRasterizer();
pdfRasterizer.pdfToImage(source, tmp, null, null); pdfRasterizer.pdfToImage(source, tmp, null, null);
Path tmpTarget = tmp.resolve(target.getFileName()); Path tmpTarget = tmp.resolve(target.getFileName());
int pagecount = pdfRasterizer.mergeImagesToPDF(tmp, tmpTarget); int pagecount = pdfRasterizer.mergeImagesToPDF(tmp, tmpTarget);
@ -74,9 +68,7 @@ public class PDFRasterizerTest {
try { try {
delete(target); delete(target);
Files.createDirectories(target); Files.createDirectories(target);
PDFRasterizer rasterizer = new PDFRasterizer( PDFRasterizer rasterizer = new PDFRasterizer();
"org.xbib.graphics.ghostscript", "Jörg Prante",
"converted from " + p);
rasterizer.pdfToImage(p, target, "pdf-", "1-"); rasterizer.pdfToImage(p, target, "pdf-", "1-");
rasterizer.close(); rasterizer.close();
} catch (IOException e) { } catch (IOException e) {
@ -90,7 +82,6 @@ public class PDFRasterizerTest {
@Test @Test
public void testPDFRasterizerConvert() throws Exception { public void testPDFRasterizerConvert() throws Exception {
logger.log(Level.INFO, "testing java.io.tmpdir = " + System.getProperty("java.io.tmpdir"));
Path path = Paths.get("build/resources/test"); Path path = Paths.get("build/resources/test");
try (Stream<Path> stream = Files.list(path)) { try (Stream<Path> stream = Files.list(path)) {
stream.forEach(p -> { stream.forEach(p -> {
@ -100,9 +91,7 @@ public class PDFRasterizerTest {
try { try {
delete(target); delete(target);
Files.createDirectories(target.getParent()); Files.createDirectories(target.getParent());
PDFRasterizer rasterizer = new PDFRasterizer( PDFRasterizer rasterizer = new PDFRasterizer();
"org.xbib.graphics.ghostscript", "Jörg Prante",
"converted from " + p);
rasterizer.convert(p, target); rasterizer.convert(p, target);
rasterizer.close(); rasterizer.close();
} catch (IOException e) { } catch (IOException e) {

View file

@ -32,14 +32,11 @@ public class TiffTest {
@Test @Test
public void mergeTiff() throws IOException { public void mergeTiff() throws IOException {
String creator = "Malva PDF";
String author = "Jörg Prante";
String subject = "Test";
Path sourceDir = Paths.get("src/test/resources/org/xbib/graphics/ghostscript/test/"); Path sourceDir = Paths.get("src/test/resources/org/xbib/graphics/ghostscript/test/");
Path targetFile = Paths.get("build/tmp.pdf"); Path targetFile = Paths.get("build/tmp.pdf");
PDFRasterizer pdfRasterizer = new PDFRasterizer(creator, author, subject); PDFRasterizer pdfRasterizer = new PDFRasterizer();
int pagecount = pdfRasterizer.mergeImagesToPDF(sourceDir, targetFile); int pagecount = pdfRasterizer.mergeImagesToPDF(sourceDir, targetFile, "**/*.tif");
logger.info("pagecount = " + pagecount); logger.info("pagecount = " + pagecount);
assertEquals(3, pagecount); assertEquals(2, pagecount);
} }
} }

View file

@ -370,7 +370,7 @@ abstract class BaseBuilderSpec extends Specification {
when: when:
List layout = [ List layout = [
[ key: 'Typ', value: 'Online', 'bold':true], [ key: 'Typ', value: 'Online', 'bold':true],
[ key: 'Medea-Nummer', value: 'test'], [ key: 'Nummer', value: 'test'],
[ key: 'Bestelldatum', value: 'test'], [ key: 'Bestelldatum', value: 'test'],
[ key: 'Eingangsdatum', value: 'test'], [ key: 'Eingangsdatum', value: 'test'],
[ key: 'Besteller', value: 'test', line: true], [ key: 'Besteller', value: 'test', line: true],
@ -399,7 +399,7 @@ abstract class BaseBuilderSpec extends Specification {
paragraph(margin:[left: 6.cm, right: 1.cm, top: -1.5.cm]) { paragraph(margin:[left: 6.cm, right: 1.cm, top: -1.5.cm]) {
font.size = 24.pt font.size = 24.pt
font.bold = true font.bold = true
text 'Aufsatzbestellung Lieferschein' text 'Lieferschein'
} }
paragraph { paragraph {
table(margin:[left: 1.cm, top: 2.cm], width: 19.cm, padding: 0.pt, border:[size:0.pt]) { table(margin:[left: 1.cm, top: 2.cm], width: 19.cm, padding: 0.pt, border:[size:0.pt]) {

View file

@ -28,13 +28,13 @@ class FontSpec extends Specification {
} }
def "printable characters"() { def "printable characters"() {
String s = "\u0098 Hello Jörg" String s = "\u0098 Hello World"
when: when:
s = s.replaceAll("\\p{C}", "") s = s.replaceAll("\\p{C}", "")
then: then:
s == " Hello Jörg" s == " Hello World"
} }
def "glyph exists"() { def "glyph exists"() {

View file

@ -9,6 +9,8 @@ import java.nio.file.Files
import java.nio.file.Paths import java.nio.file.Paths
import java.util.regex.Pattern import java.util.regex.Pattern
import static org.junit.Assert.assertTrue
@Log4j2 @Log4j2
class PdfDocumentBuilderTest { class PdfDocumentBuilderTest {
@ -48,7 +50,7 @@ class PdfDocumentBuilderTest {
PdfDocumentBuilder builder = new PdfDocumentBuilder(outputStream) PdfDocumentBuilder builder = new PdfDocumentBuilder(outputStream)
List layout = [ List layout = [
[key: 'Typ', value: 'Online', 'bold': true], [key: 'Typ', value: 'Online', 'bold': true],
[key: 'Medea-Nummer', value: 'test'], [key: 'Nummer', value: 'test'],
[key: 'Bestelldatum', value: 'test'], [key: 'Bestelldatum', value: 'test'],
[key: 'Eingangsdatum', value: 'test'], [key: 'Eingangsdatum', value: 'test'],
[key: 'Besteller', value: 'test', line: true], [key: 'Besteller', value: 'test', line: true],
@ -147,7 +149,7 @@ class PdfDocumentBuilderTest {
@Test @Test
void testPdfWithImage() { void testPdfWithImage() {
byte[] logo = getClass().getResourceAsStream('/img/logo-print.png').bytes byte[] logo = getClass().getResourceAsStream('/img/img.png').bytes
OutputStream outputStream = Files.newOutputStream(Paths.get("build/testimage.pdf")) OutputStream outputStream = Files.newOutputStream(Paths.get("build/testimage.pdf"))
outputStream.withCloseable { outputStream.withCloseable {
PdfDocumentBuilder builder = new PdfDocumentBuilder(outputStream) PdfDocumentBuilder builder = new PdfDocumentBuilder(outputStream)
@ -159,7 +161,7 @@ class PdfDocumentBuilderTest {
builder.create { builder.create {
document(font: [family: 'Helvetica'], margin: [top: 1.cm]) { document(font: [family: 'Helvetica'], margin: [top: 1.cm]) {
paragraph(margin: [left: 7.mm]) { paragraph(margin: [left: 7.mm]) {
image(data: logo, name: 'logo-print.png', width: 125.px, height: 45.px) image(data: logo, name: 'img.png', width: 125.px, height: 45.px)
} }
paragraph(margin: [left: 6.cm, right: 1.cm, top: 0.cm]) { paragraph(margin: [left: 6.cm, right: 1.cm, top: 0.cm]) {
font.size = 24.pt font.size = 24.pt
@ -229,11 +231,12 @@ class PdfDocumentBuilderTest {
Pattern detectHan = Pattern.compile('.*\\p{script=Han}.*') Pattern detectHan = Pattern.compile('.*\\p{script=Han}.*')
Pattern detectLatin = Pattern.compile('.*\\p{script=Latin}.*') Pattern detectLatin = Pattern.compile('.*\\p{script=Latin}.*')
String chinese = "北京 東京大学" String chinese = "北京 東京大学"
String caron = "Hey Jörg, this is Latin Small Letter C with Caron \u010d" String caron = "Hey, this is Latin Small Letter C with Caron \u010d"
log.info("chinese = ${detectHan.matcher(chinese).matches()}") log.info("chinese = ${detectHan.matcher(chinese).matches()}")
assertTrue(detectHan.matcher(chinese).matches())
log.info("caron = ${detectLatin.matcher(caron).matches()}") log.info("caron = ${detectLatin.matcher(caron).matches()}")
assertTrue(detectLatin.matcher(caron).matches())
String normalized = caron.replaceAll("\\P{IsLatin}","") String normalized = caron.replaceAll("\\P{IsLatin}","")
log.info("normalized=${normalized}") log.info("normalized=${normalized}")
} }
} }

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 673 B

View file

@ -5,3 +5,19 @@ https://github.com/ralfstuckert/pdfbox-layout
(MIT License) (MIT License)
as of October, 2020 as of October, 2020
and extended by "easytable"
https://github.com/vandeseer/easytable
(MIT License)
as of March, 2021
and extended by "boxable"
https://github.com/dhorions/boxable
(Apache 2.0 License)
as of March, 2021

View file

@ -211,119 +211,4 @@ public abstract class AbstractCell {
public boolean isVerticallyAligned(VerticalAlignment alignment) { public boolean isVerticallyAligned(VerticalAlignment alignment) {
return getSettings().getVerticalAlignment() == alignment; return getSettings().getVerticalAlignment() == alignment;
} }
/*public abstract static class AbstractCellBuilder<C extends AbstractCell, B extends AbstractCell.AbstractCellBuilder<C, B>> {
protected Settings settings = new Settings();
// We don't want to expose settings directly!
private void settings(Settings settings) {}
public B borderWidth(final float borderWidth) {
settings.setBorderWidthTop(borderWidth);
settings.setBorderWidthBottom(borderWidth);
settings.setBorderWidthLeft(borderWidth);
settings.setBorderWidthRight(borderWidth);
return (B) this;
}
public B borderWidthTop(final float borderWidth) {
settings.setBorderWidthTop(borderWidth);
return (B) this;
}
public B borderWidthBottom(final float borderWidth) {
settings.setBorderWidthBottom(borderWidth);
return (B) this;
}
public B borderWidthLeft(final float borderWidth) {
settings.setBorderWidthLeft(borderWidth);
return (B) this;
}
public B borderWidthRight(final float borderWidth) {
settings.setBorderWidthRight(borderWidth);
return (B) this;
}
public B borderStyleTop(final BorderStyleInterface style) {
settings.setBorderStyleTop(style);
return (B) this;
}
public B borderStyleBottom(final BorderStyleInterface style) {
settings.setBorderStyleBottom(style);
return (B) this;
}
public B borderStyleLeft(final BorderStyleInterface style) {
settings.setBorderStyleLeft(style);
return (B) this;
}
public B borderStyleRight(final BorderStyleInterface style) {
settings.setBorderStyleRight(style);
return (B) this;
}
public B borderStyle(final BorderStyleInterface style) {
return this.borderStyleLeft(style)
.borderStyleRight(style)
.borderStyleBottom(style)
.borderStyleTop(style);
}
public B padding(final float padding) {
return this.paddingTop(padding)
.paddingBottom(padding)
.paddingLeft(padding)
.paddingRight(padding);
}
public B paddingTop(final float padding) {
settings.setPaddingTop(padding);
return (B) this;
}
public B paddingBottom(final float padding) {
settings.setPaddingBottom(padding);
return (B) this;
}
public B paddingLeft(final float padding) {
settings.setPaddingLeft(padding);
return (B) this;
}
public B paddingRight(final float padding) {
settings.setPaddingRight(padding);
return (B) this;
}
public B horizontalAlignment(final HorizontalAlignment alignment) {
settings.setHorizontalAlignment(alignment);
return (B) this;
}
public B verticalAlignment(final VerticalAlignment alignment) {
settings.setVerticalAlignment(alignment);
return (B) this;
}
public B backgroundColor(final Color backgroundColor) {
settings.setBackgroundColor(backgroundColor);
return (B) this;
}
public B borderColor(final Color borderColor) {
settings.setBorderColor(borderColor);
return (B) this;
}
public B wordBreak(final Boolean wordBreak) {
settings.setWordBreak(wordBreak);
return (B) this;
}
}*/
} }

View file

@ -78,23 +78,4 @@ public abstract class AbstractTextCell extends AbstractCell {
public float getMaxWidth() { public float getMaxWidth() {
return getMaxWidthOfText() - getHorizontalPadding(); return getMaxWidthOfText() - getHorizontalPadding();
} }
/*public abstract static class AbstractTextCellBuilder<C extends AbstractTextCell, B extends AbstractTextCell.AbstractTextCellBuilder<C, B>> extends AbstractCellBuilder<C, B> {
public B font(final Font font) {
settings.setFont(font);
return (B) this;
}
public B fontSize(final Integer fontSize) {
settings.setFontSize(fontSize);
return (B) this;
}
public B textColor(final Color textColor) {
settings.setTextColor(textColor);
return (B) this;
}
}*/
} }

View file

@ -76,59 +76,5 @@ public class ParagraphCell extends AbstractCell {
public org.xbib.graphics.pdfbox.layout.elements.Paragraph getWrappedParagraph() { public org.xbib.graphics.pdfbox.layout.elements.Paragraph getWrappedParagraph() {
return wrappedParagraph; return wrappedParagraph;
} }
/*public static class ParagraphBuilder {
private final List<ParagraphProcessable> processables = new LinkedList<>();
private ParagraphBuilder() {
}
public ParagraphBuilder append(StyledText styledText) {
processables.add(styledText);
return this;
}
public ParagraphBuilder append(Hyperlink hyperlink) {
processables.add(hyperlink);
return this;
}
public ParagraphBuilder append(Markup markup) {
processables.add(markup);
return this;
}
public ParagraphBuilder appendNewLine(Font font, float fontSize) {
processables.add(new NewLine(font, fontSize));
return this;
}
public Paragraph build() {
return new Paragraph(processables);
} }
} }
public static ParagraphBuilder builder() {
return new ParagraphBuilder();
}*/
}
/*public abstract static class ParagraphCellBuilder<C extends ParagraphCell, B extends ParagraphCell.ParagraphCellBuilder<C, B>> extends AbstractCellBuilder<C, B> {
public B font(final Font font) {
settings.setFont(font);
return (B) this;
}
public B fontSize(final Integer fontSize) {
settings.setFontSize(fontSize);
return (B) this;
}
public B textColor(final Color textColor) {
settings.setTextColor(textColor);
return (B) this;
}
}*/
}

View file

@ -26,7 +26,7 @@ public final class PdfUtil {
* @param fontSize FontSize of String * @param fontSize FontSize of String
* @return Width (in points) * @return Width (in points)
*/ */
public static float getStringWidth(final String text, final Font font, final int fontSize) { public static float getStringWidth(String text, Font font, int fontSize) {
return Arrays.stream(text.split(NEW_LINE_REGEX)) return Arrays.stream(text.split(NEW_LINE_REGEX))
.max(Comparator.comparing(String::length)) .max(Comparator.comparing(String::length))
.map(x -> { .map(x -> {
@ -40,25 +40,20 @@ public final class PdfUtil {
} }
private static float getWidthOfStringWithoutNewlines(String text, Font font, int fontSize) throws IOException { private static float getWidthOfStringWithoutNewlines(String text, Font font, int fontSize) throws IOException {
List<String> codePointsAsString = text.codePoints()
final List<String> codePointsAsString = text.codePoints()
.mapToObj(codePoint -> new String(new int[]{codePoint}, 0, 1)) .mapToObj(codePoint -> new String(new int[]{codePoint}, 0, 1))
.collect(Collectors.toList()); .collect(Collectors.toList());
List<Float> widths = new ArrayList<>(); List<Float> widths = new ArrayList<>();
for (String codepoint : codePointsAsString) {
for (final String codepoint : codePointsAsString) {
try { try {
widths.add(font.getRegularFont().getStringWidth(codepoint) * fontSize / 1000F); widths.add(font.getRegularFont().getStringWidth(codepoint) * fontSize / 1000F);
} catch (final IllegalArgumentException | IOException e) { } catch (final IllegalArgumentException | IOException e) {
widths.add(font.getRegularFont().getStringWidth("") * fontSize / 1000F); widths.add(font.getRegularFont().getStringWidth("") * fontSize / 1000F);
} }
} }
return widths.stream().reduce(0.0f, Float::sum); return widths.stream().reduce(0.0f, Float::sum);
} }
/** /**
* Computes the height of a font. * Computes the height of a font.
* *
@ -66,7 +61,7 @@ public final class PdfUtil {
* @param fontSize FontSize * @param fontSize FontSize
* @return Height of font * @return Height of font
*/ */
public static float getFontHeight(Font font, final int fontSize) { public static float getFontHeight(Font font, int fontSize) {
return font.getRegularFont().getFontDescriptor().getCapHeight() * fontSize / 1000F; return font.getRegularFont().getFontDescriptor().getCapHeight() * fontSize / 1000F;
} }
@ -79,21 +74,20 @@ public final class PdfUtil {
* @param maxWidth Maximal width of resulting text-lines * @param maxWidth Maximal width of resulting text-lines
* @return A list of lines, where all are smaller than maxWidth * @return A list of lines, where all are smaller than maxWidth
*/ */
public static List<String> getOptimalTextBreakLines(final String text, final Font font, final int fontSize, final float maxWidth) { public static List<String> getOptimalTextBreakLines(String text, Font font, int fontSize, float maxWidth) {
List<String> result = new ArrayList<>(); List<String> result = new ArrayList<>();
for (final String line : text.split(NEW_LINE_REGEX)) { for (String line : text.split(NEW_LINE_REGEX)) {
if (PdfUtil.doesTextLineFit(line, font, fontSize, maxWidth)) { if (PdfUtil.doesTextLineFit(line, font, fontSize, maxWidth)) {
result.add(line); result.add(line);
} else { } else {
result.addAll(PdfUtil.wrapLine(line, font, fontSize, maxWidth)); result.addAll(PdfUtil.wrapLine(line, font, fontSize, maxWidth));
} }
} }
return result; return result;
} }
private static List<String> wrapLine(final String line, final Font font, final int fontSize, final float maxWidth) { private static List<String> wrapLine(String line, Font font, int fontSize, float maxWidth) {
if (PdfUtil.doesTextLineFit(line, font, fontSize, maxWidth)) { if (doesTextLineFit(line, font, fontSize, maxWidth)) {
return Collections.singletonList(line); return Collections.singletonList(line);
} }
List<String> goodLines = new ArrayList<>(); List<String> goodLines = new ArrayList<>();
@ -106,7 +100,7 @@ public final class PdfUtil {
return goodLines; return goodLines;
} }
private static List<String> splitBySize(final String line, final Font font, final int fontSize, final float maxWidth) { private static List<String> splitBySize(String line, Font font, int fontSize, float maxWidth) {
List<String> returnList = new ArrayList<>(); List<String> returnList = new ArrayList<>();
for (int i = line.length() - 1; i > 0; i--) { for (int i = line.length() - 1; i > 0; i--) {
String fittedNewLine = line.substring(0, i) + "-"; String fittedNewLine = line.substring(0, i) + "-";
@ -120,11 +114,10 @@ public final class PdfUtil {
return returnList; return returnList;
} }
private static String buildALine(Stack<String> words,
private static String buildALine(final Stack<String> words, Font font,
final Font font, int fontSize,
final int fontSize, float maxWidth) {
final float maxWidth) {
StringBuilder line = new StringBuilder(); StringBuilder line = new StringBuilder();
float width = 0; float width = 0;
while (!words.empty()) { while (!words.empty()) {

View file

@ -0,0 +1,3 @@
dependencies {
api "org.apache.pdfbox:pdfbox:${project.property('pdfbox.version')}"
}

View file

@ -0,0 +1,6 @@
module org.xbib.graphics.pdfbox.print {
exports org.xbib.graphics.pdfbox.print;
requires java.logging;
requires transitive java.desktop;
requires org.apache.pdfbox;
}

View file

@ -1,4 +1,7 @@
package org.xbib.graphics.printer; package org.xbib.graphics.pdfbox.print;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPageable;
import javax.print.Doc; import javax.print.Doc;
import javax.print.DocFlavor; import javax.print.DocFlavor;
@ -18,6 +21,7 @@ import javax.print.attribute.standard.PrinterMakeAndModel;
import javax.print.attribute.standard.SheetCollate; import javax.print.attribute.standard.SheetCollate;
import javax.print.attribute.standard.Sides; import javax.print.attribute.standard.Sides;
import java.awt.print.PrinterJob;
import java.io.InputStream; import java.io.InputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -27,7 +31,12 @@ import java.util.List;
*/ */
public class PrintUtility { public class PrintUtility {
public static void print(InputStream inputStream, Printer printer) public static void print(InputStream inputStream, DocFlavor docFlavor)
throws Exception {
print(inputStream, docFlavor, findDefaultPrinter(docFlavor));
}
public static void print(InputStream inputStream, DocFlavor docFlavor, Printer printer)
throws Exception { throws Exception {
if (inputStream == null || printer == null) { if (inputStream == null || printer == null) {
return; return;
@ -51,7 +60,7 @@ public class PrintUtility {
pas.add(Sides.TUMBLE); pas.add(Sides.TUMBLE);
break; break;
default: default:
pas.add(Sides.ONE_SIDED); break;
} }
} }
if (printer.isModeSupported()) { if (printer.isModeSupported()) {
@ -63,7 +72,7 @@ public class PrintUtility {
pas.add(Chromaticity.COLOR); pas.add(Chromaticity.COLOR);
break; break;
default: default:
pas.add(Chromaticity.MONOCHROME); break;
} }
} }
if (printer.isMediaSupported() && printer.getMediaSize() != null) { if (printer.isMediaSupported() && printer.getMediaSize() != null) {
@ -74,15 +83,22 @@ public class PrintUtility {
} }
PrintService service = printer.getService(); PrintService service = printer.getService();
DocPrintJob job = service.createPrintJob(); DocPrintJob job = service.createPrintJob();
Doc doc = new SimpleDoc(inputStream, Doc doc = new SimpleDoc(inputStream, docFlavor, null);
DocFlavor.INPUT_STREAM.POSTSCRIPT, null);
job.print(doc, pas); job.print(doc, pas);
} }
public static Printer getPrinter(String printerName) { public static void print(InputStream inputStream, Printer printer) throws Exception {
PDDocument document = PDDocument.load(inputStream);
PrinterJob job = PrinterJob.getPrinterJob();
job.setPageable(new PDFPageable(document));
job.setPrintService(printer.getService());
job.print();
}
public static Printer getPrinter(String printerName, DocFlavor docFlavor) {
Printer printer = null; Printer printer = null;
if (printerName != null) { if (printerName != null) {
List<Printer> printers = findPrinters(); List<Printer> printers = findPrinters(docFlavor);
for (Printer p : printers) { for (Printer p : printers) {
if (printerName.equalsIgnoreCase(p.getName())) { if (printerName.equalsIgnoreCase(p.getName())) {
printer = p; printer = p;
@ -94,21 +110,18 @@ public class PrintUtility {
PrintService service = PrintServiceLookup.lookupDefaultPrintService(); PrintService service = PrintServiceLookup.lookupDefaultPrintService();
printer = createPrinter(service); printer = createPrinter(service);
} }
if (printer != null) {
printer.setCopies(1);
printer.setCollate(false);
printer.setDuplex(Printer.DUPLEX_SIMPLEX);
printer.setMode(Printer.STATUS_ACCEPTING_JOBS);
printer.setMediaSize("A4");
}
return printer; return printer;
} }
public static List<Printer> findPrinters() { public static Printer findDefaultPrinter(DocFlavor docFlavor) {
List<Printer> printers = findPrinters(docFlavor);
return printers.isEmpty() ? null : printers.get(0);
}
public static List<Printer> findPrinters(DocFlavor docFlavor) {
List<Printer> printers = new ArrayList<>(); List<Printer> printers = new ArrayList<>();
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet(); PrintRequestAttributeSet printRequestAttributeSet = new HashPrintRequestAttributeSet();
DocFlavor flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT; PrintService[] printServices = PrintServiceLookup.lookupPrintServices(docFlavor, printRequestAttributeSet);
PrintService[] printServices = PrintServiceLookup.lookupPrintServices(flavor, pras);
if (printServices != null) { if (printServices != null) {
for (PrintService service : printServices) { for (PrintService service : printServices) {
printers.add(createPrinter(service)); printers.add(createPrinter(service));
@ -150,11 +163,7 @@ public class PrintUtility {
if (collate == null) { if (collate == null) {
collate = SheetCollate.UNCOLLATED; collate = SheetCollate.UNCOLLATED;
} }
if (collate == SheetCollate.COLLATED) { printer.setCollate(collate == SheetCollate.COLLATED);
printer.setCollate(true);
} else {
printer.setCollate(false);
}
} }
boolean modeSupported = service.isAttributeCategorySupported(Chromaticity.class); boolean modeSupported = service.isAttributeCategorySupported(Chromaticity.class);
printer.setModeSupported(modeSupported); printer.setModeSupported(modeSupported);
@ -189,7 +198,7 @@ public class PrintUtility {
printer.setMediaSupported(mediaSupported); printer.setMediaSupported(mediaSupported);
if (mediaSupported) { if (mediaSupported) {
Object obj = service.getSupportedAttributeValues(Media.class, null, null); Object obj = service.getSupportedAttributeValues(Media.class, null, null);
if (obj != null && obj instanceof Media[]) { if (obj instanceof Media[]) {
Media[] medias = (Media[]) obj; Media[] medias = (Media[]) obj;
for (Media media : medias) { for (Media media : medias) {
if (media instanceof MediaSizeName) { if (media instanceof MediaSizeName) {

View file

@ -1,4 +1,4 @@
package org.xbib.graphics.printer; package org.xbib.graphics.pdfbox.print;
import javax.print.PrintService; import javax.print.PrintService;
import javax.print.attribute.standard.Media; import javax.print.attribute.standard.Media;
@ -29,7 +29,7 @@ public class Printer {
private int duplex; private int duplex;
private boolean mediaSupported; private boolean mediaSupported;
private String mediaSize; private String mediaSize;
private Map<String, Media> mediaSizeNames = new HashMap<>(); private final Map<String, Media> mediaSizeNames = new HashMap<>();
private int pageSize; private int pageSize;
private String pageRange; private String pageRange;
private PrintService service; private PrintService service;

View file

@ -0,0 +1,27 @@
package org.xbib.graphics.pdfbox.print.test;
import javax.print.DocFlavor;
import org.junit.jupiter.api.Test;
import org.xbib.graphics.pdfbox.print.PrintUtility;
import org.xbib.graphics.pdfbox.print.Printer;
import java.util.logging.Level;
import java.util.logging.Logger;
public class PrinterTest {
private static final Logger logger = Logger.getLogger(PrinterTest.class.getName());
@Test
public void testPrinterSelection() {
logger.log(Level.INFO, "printer = " + PrintUtility.findPrinters(DocFlavor.INPUT_STREAM.AUTOSENSE));
}
@Test
public void print() throws Exception {
Printer printer = PrintUtility.getPrinter("Samsung ML-1610 (USB001)", DocFlavor.INPUT_STREAM.AUTOSENSE);
if (printer != null) {
PrintUtility.print(getClass().getResourceAsStream("/test.pdf"), printer);
}
}
}

Binary file not shown.

View file

@ -1,5 +0,0 @@
module org.xbib.graphics.printer {
exports org.xbib.graphics.printer;
requires java.logging;
requires transitive java.desktop;
}

View file

@ -1,18 +0,0 @@
package org.xbib.graphics.printer.test;
import org.junit.jupiter.api.Test;
import org.xbib.graphics.printer.PrintUtility;
import java.util.logging.Level;
import java.util.logging.Logger;
public class PrinterTest {
private static final Logger logger = Logger.getLogger(PrinterTest.class.getName());
@Test
public void testPrinterSelection() {
logger.log(Level.INFO, "printer = " + PrintUtility.findPrinters());
}
}

View file

@ -9,6 +9,6 @@ include 'graphics-ghostscript'
include 'graphics-pdfbox' include 'graphics-pdfbox'
include 'graphics-pdfbox-layout' include 'graphics-pdfbox-layout'
include 'graphics-pdfbox-groovy' include 'graphics-pdfbox-groovy'
include 'graphics-printer' include 'graphics-pdfbox-print'
include 'graphics-graph-gral' include 'graphics-graph-gral'
include 'graphics-graph-jmathplot' include 'graphics-graph-jmathplot'