├── src ├── main │ ├── resources │ │ ├── epub │ │ │ ├── mimetype │ │ │ ├── page_styles.css │ │ │ ├── META-INF │ │ │ │ └── container.xml │ │ │ ├── stylesheet.css │ │ │ ├── titlepage.xhtml │ │ │ ├── index.html │ │ │ ├── toc.ncx │ │ │ └── content.opf │ │ └── logback.xml │ └── java │ │ └── pdf │ │ └── converter │ │ ├── img │ │ ├── ImageFileExtension.java │ │ └── ImgCreator.java │ │ ├── txt │ │ └── TxtCreator.java │ │ ├── zip │ │ └── ZipCreator.java │ │ ├── PdfConverter.java │ │ └── epub │ │ └── EpubCreator.java └── test │ ├── resources │ └── mobydick.pdf │ └── java │ └── pdf │ └── converter │ └── PdfConverterTest.java ├── .gitignore ├── sonar-project.properties ├── .travis.yml ├── README.md ├── .github └── workflows │ └── codeql-analysis.yml ├── LICENSE └── pom.xml /src/main/resources/epub/mimetype: -------------------------------------------------------------------------------- 1 | application/epub+zip -------------------------------------------------------------------------------- /src/main/resources/epub/page_styles.css: -------------------------------------------------------------------------------- 1 | @page { 2 | margin-bottom: 5pt; 3 | margin-top: 5pt 4 | } 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | .idea 3 | build 4 | *.iml 5 | gradle 6 | gradlew 7 | *.bat 8 | *.log 9 | target 10 | -------------------------------------------------------------------------------- /src/test/resources/mobydick.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jmrozanec/pdf-converter/HEAD/src/test/resources/mobydick.pdf -------------------------------------------------------------------------------- /src/main/java/pdf/converter/img/ImageFileExtension.java: -------------------------------------------------------------------------------- 1 | package pdf.converter.img; 2 | 3 | public enum ImageFileExtension { 4 | PNG, JPG; 5 | } 6 | -------------------------------------------------------------------------------- /src/main/resources/epub/META-INF/container.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /src/main/resources/epub/stylesheet.css: -------------------------------------------------------------------------------- 1 | .pdf-converter { 2 | display: block; 3 | font-size: 1em; 4 | padding-left: 0; 5 | padding-right: 0; 6 | margin: 0 5pt 7 | } 8 | .pdf-converter1 { 9 | display: block; 10 | margin: 1em 0 11 | } 12 | .pdf-converter2 { 13 | height: auto; 14 | width: auto 15 | } 16 | -------------------------------------------------------------------------------- /src/main/resources/epub/titlepage.xhtml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Cover 7 | 11 | 12 | 13 |
14 |

$TITLE

15 |
16 | 17 | -------------------------------------------------------------------------------- /sonar-project.properties: -------------------------------------------------------------------------------- 1 | # must be unique in a given SonarQube instance 2 | sonar.projectKey=pdf-converter 3 | # this is the name and version displayed in the SonarQube UI. Was mandatory prior to SonarQube 6.1. 4 | #sonar.projectName=cron-utils 5 | #sonar.projectVersion=7.0.1-SNAPSHOT 6 | 7 | # Path is relative to the sonar-project.properties file. Replace "\" by "/" on Windows. 8 | # This property is optional if sonar.modules is set. 9 | sonar.sources=src/main/java 10 | sonar.tests=src/test/java 11 | sonar.java.binaries=target/classes 12 | 13 | 14 | # Encoding of the source code. Default is default system encoding 15 | sonar.sourceEncoding=UTF-8 16 | -------------------------------------------------------------------------------- /src/main/resources/epub/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | index 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | $CONTENT 13 |

14 | 15 | -------------------------------------------------------------------------------- /src/main/resources/epub/toc.ncx: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | $TITLE 12 | 13 | 14 | 15 | 16 | Start 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/test/java/pdf/converter/PdfConverterTest.java: -------------------------------------------------------------------------------- 1 | package pdf.converter; 2 | 3 | import org.junit.Assert; 4 | import org.junit.Test; 5 | 6 | import java.io.File; 7 | import java.io.IOException; 8 | import java.nio.file.Files; 9 | import java.nio.file.Path; 10 | import java.nio.file.StandardCopyOption; 11 | import java.util.UUID; 12 | 13 | public class PdfConverterTest { 14 | 15 | @Test 16 | public void convert() throws Exception { 17 | Path path = copyToTmp(); 18 | File dest = new File(path.toFile(), "mobydick.epub"); 19 | PdfConverter 20 | .convert(new File(path.toFile(), "mobydick.pdf")) 21 | .intoEpub("Moby Dick", dest); 22 | Assert.assertTrue(dest.exists()); 23 | } 24 | 25 | private Path copyToTmp() throws IOException { 26 | Path tmpdir = new File(String.format("/tmp/%s", UUID.randomUUID().toString())).toPath(); 27 | System.out.println(tmpdir); 28 | Files.createDirectories(tmpdir); 29 | Path dest = new File(tmpdir.toFile(), "mobydick.pdf").toPath(); 30 | ClassLoader classLoader = getClass().getClassLoader(); 31 | Path file = new File(classLoader.getResource("mobydick.pdf").getFile()).toPath(); 32 | Files.copy(file, dest, StandardCopyOption.REPLACE_EXISTING); 33 | return tmpdir; 34 | } 35 | } -------------------------------------------------------------------------------- /src/main/resources/epub/content.opf: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | en 5 | $AUTHOR 6 | 7 | $TITLE 8 | 9 | pdf-converter 10 | $UUID 11 | 12 | 13 | 14 | $CONTENT 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /src/main/java/pdf/converter/txt/TxtCreator.java: -------------------------------------------------------------------------------- 1 | package pdf.converter.txt; 2 | 3 | import org.apache.pdfbox.io.RandomAccessFile; 4 | import org.apache.pdfbox.pdmodel.PDDocument; 5 | import org.apache.pdfbox.text.PDFTextStripper; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | 9 | import java.io.File; 10 | import java.io.FileWriter; 11 | import java.io.IOException; 12 | import java.util.UUID; 13 | 14 | public class TxtCreator { 15 | private static final Logger log = LoggerFactory.getLogger(TxtCreator.class); 16 | 17 | public void process(File pdf, File output){ 18 | PDDocument pdDoc; 19 | try {//Kudos for closing: http://stackoverflow.com/questions/156508/closing-a-java-fileinputstream 20 | pdDoc = PDDocument.load(pdf); 21 | FileWriter writer = new FileWriter(output); 22 | try { 23 | PDFTextStripper stripper = new PDFTextStripper(); 24 | int numberOfPages = pdDoc.getNumberOfPages(); 25 | 26 | for (int j = 1; j < numberOfPages+1; j++) { 27 | stripper.setStartPage(j); 28 | stripper.setEndPage(j); 29 | writer.write(stripper.getText(pdDoc)); 30 | writer.flush(); 31 | } 32 | } finally { 33 | pdDoc.close(); 34 | writer.close(); 35 | } 36 | } catch (IOException ioe) { 37 | log.warn(String.format("Failed to create txt for file: %s", pdf.getName()), ioe); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/pdf/converter/zip/ZipCreator.java: -------------------------------------------------------------------------------- 1 | package pdf.converter.zip; 2 | import org.slf4j.Logger; 3 | import org.slf4j.LoggerFactory; 4 | 5 | import java.io.*; 6 | import java.nio.file.Files; 7 | import java.nio.file.Path; 8 | import java.nio.file.Paths; 9 | import java.util.zip.ZipEntry; 10 | import java.util.zip.ZipOutputStream; 11 | 12 | public class ZipCreator { 13 | private static final Logger log = LoggerFactory.getLogger(ZipCreator.class); 14 | 15 | public void create(File imgsDir, File output) throws IOException { 16 | pack(imgsDir.getAbsolutePath(), output.getAbsolutePath()); 17 | } 18 | 19 | private static void pack(String sourceDirPath, String zipFilePath) throws IOException { 20 | Path p = Files.createFile(Paths.get(zipFilePath)); 21 | try (ZipOutputStream zs = new ZipOutputStream(Files.newOutputStream(p))) { 22 | Path pp = Paths.get(sourceDirPath); 23 | Files.walk(pp) 24 | .filter(path -> !Files.isDirectory(path)) 25 | .forEach(path -> { 26 | ZipEntry zipEntry = new ZipEntry(pp.relativize(path).toString()); 27 | try { 28 | zs.putNextEntry(zipEntry); 29 | zs.write(Files.readAllBytes(path)); 30 | zs.closeEntry(); 31 | } catch (Exception e) { 32 | log.warn("Failed to create zip file", e); 33 | } 34 | }); 35 | } 36 | } 37 | } 38 | 39 | 40 | -------------------------------------------------------------------------------- /src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | 7 | %d{ISO8601} %p %t %c{0}.%M - %m%n 8 | utf8 9 | 10 | 11 | 12 | 13 | pdf-converter.log 14 | 15 | 16 | pdf-converter.%d{yyyy-MM-dd}.%i.log 17 | 19 | 20 | 50MB 21 | 22 | 23 | 24 | 7 25 | 26 | 27 | %d{ISO8601} %p %t %c{0}.%M - %m%n 28 | utf8 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | 3 | branches: 4 | only: 5 | - master 6 | 7 | jdk: 8 | - oraclejdk11 9 | 10 | before_install: "git clone -b travis `git config --get remote.origin.url` target/travis" 11 | 12 | addons: 13 | apt: 14 | packages: 15 | - ghostscript 16 | sonarcloud: 17 | organization: "jmrozanec-github" 18 | token: 19 | secure: "eLi07vooUivdhdChr/4VJUZyGDeQuFSymlwqinpgNPofUOJRRUXqvg1UBggywOJUjwa/6UM08SRc1RPRiqRgY50Ke3NueHbFk+MBIJjyrKo/hPqtUeXkUjtE/Uy64Kju/5n4xAt5FswO1HKJsrQoFAuKo/g46DXJocnYgkWm7xalal3Y3B3rZ5y8M2m5vFHlFoAY2oXbO9tV39XeFMkboLTNB/7brJA1oKlUhv9lZBzsQ22A+oiy9d39QUJbxQntLCeGm1GLnL6ed+5f6gFf+hvv5NgfA1I/ZDsZfbGyNN4dgLYemuXcI4ncMWu2v3F2POqkPGZ8Erc1f1e8rEOW7h3Z/c/KD1of9P+P4FMLM6u+B0GN0BtAq6CP9lxOKwPmzFOrTD0nvUkh4DQnzSPWfsltSxvHRuya+1rbEeYmRiL5Gp+h1ZrJWurLaW8+qSrTva3X9P7dv5g8wYW1BaHrDAyfY7vYjLEfH9QNUNA7FuEUYtFOe1RlVEOb5GECcSpoaPVSeV+TmwiEudbIW/mXrgTocqoKjtZ4Xm0X3Jm4hzCRjpBKL3CM6ojHdra886QQk8EgQypnrlCaS40MeG8smA9xfrq32vltT1IPCuwb1w6zBvg1ms+iRcU+jaK4RZEhHvCJtuG8sLZxRqBawBySMybPxpzms1FGn2RfUS2gNao=" 20 | script: 21 | - > 22 | if [ "$TRAVIS_PULL_REQUEST" != "false" ];then 23 | mvn org.jacoco:jacoco-maven-plugin:prepare-agent package --settings target/travis/settings.xml -Dsettings.security=target/travis/settings-security.xml -Dmaven.javadoc.skip=true; 24 | sonar-scanner 25 | fi 26 | - > 27 | if [ "$TRAVIS_PULL_REQUEST" = "false" ];then 28 | mvn org.jacoco:jacoco-maven-plugin:prepare-agent package deploy --settings target/travis/settings.xml -Dsettings.security=target/travis/settings-security.xml -Dmaven.javadoc.skip=true; 29 | sonar-scanner 30 | fi 31 | 32 | cache: 33 | directories: 34 | - '$HOME/.m2/repository' 35 | - '$HOME/.sonar/cache' 36 | 37 | after_success: 38 | - mvn cobertura:cobertura coveralls:cobertura 39 | - bash <(curl -s https://codecov.io/bash) 40 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | pdf-converter 2 | =========== 3 | A Java library to convert .pdf files into .epub, .txt, .png, .jpg, .zip formats. The project follows the [Semantic Versioning Convention](http://semver.org/) and uses Apache 2.0 license. 4 | 5 | [![Gitter Chat](http://img.shields.io/badge/chat-online-brightgreen.svg)](https://gitter.im/pdf-converter/) 6 | [![Build Status](https://travis-ci.org/jmrozanec/pdf-converter.svg?branch=master)](https://travis-ci.org/jmrozanec/pdf-converter) 7 | [![Coverage Status](https://coveralls.io/repos/github/jmrozanec/pdf-converter/badge.svg?branch=master)](https://coveralls.io/github/jmrozanec/pdf-converter?branch=master) 8 | 9 | **Download** 10 | 11 | pdf-converter is available on [Maven central](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.bit-scout%22) repository. 12 | 13 | 14 | com.bit-scout 15 | pdf-converter 16 | 1.0.2 17 | 18 | 19 | **Features** 20 | 21 | Any .pdf file can be converted to the following formats: 22 | * .epub: output file can either contain images of .pdf pages or their transcript. 23 | * .txt: contains the transcript of the .pdf file 24 | * .png: all pages converted to .png images 25 | * .jpg: all pages converted to .jpg images 26 | * .zip: contains images for all pages from the .pdf in the original resolution. Images can be either in .png or .jpg format. 27 | 28 | 29 | **Example** 30 | 31 | ```java 32 | 33 | PdfConverter 34 | .convert(new File(mobydick.pdf)) 35 | .intoEpub("Moby Dick", new File("mobydick.epub")); 36 | ``` 37 | 38 | **Contribute & Support!** 39 | 40 | Contributions are welcome! You can contribute by 41 | * starring and/or Flattring this repo! 42 | * requesting or adding new features. 43 | * enhancing existing code: ex.: provide more accurate description cases 44 | * testing 45 | * enhancing documentation 46 | * providing translations to support new locales 47 | * bringing suggestions and reporting bugs 48 | * spreading the word / telling us how you use it! 49 | 50 | Support us donating once or by subscription through Flattr! 51 | 52 | [![Flattr this!](https://api.flattr.com/button/flattr-badge-large.png)](https://flattr.com/submit/auto?user_id=jmrozanec&url=https://github.com/jmrozanec/pdf-converter) 53 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | name: "CodeQL" 7 | 8 | on: 9 | push: 10 | branches: [master] 11 | pull_request: 12 | # The branches below must be a subset of the branches above 13 | branches: [master] 14 | schedule: 15 | - cron: '0 14 * * 6' 16 | 17 | jobs: 18 | analyze: 19 | name: Analyze 20 | runs-on: ubuntu-latest 21 | 22 | strategy: 23 | fail-fast: false 24 | matrix: 25 | # Override automatic language detection by changing the below list 26 | # Supported options are ['csharp', 'cpp', 'go', 'java', 'javascript', 'python'] 27 | language: ['java'] 28 | # Learn more... 29 | # https://docs.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#overriding-automatic-language-detection 30 | 31 | steps: 32 | - name: Checkout repository 33 | uses: actions/checkout@v2 34 | with: 35 | # We must fetch at least the immediate parents so that if this is 36 | # a pull request then we can checkout the head. 37 | fetch-depth: 2 38 | 39 | # If this run was triggered by a pull request event, then checkout 40 | # the head of the pull request instead of the merge commit. 41 | - run: git checkout HEAD^2 42 | if: ${{ github.event_name == 'pull_request' }} 43 | 44 | # Initializes the CodeQL tools for scanning. 45 | - name: Initialize CodeQL 46 | uses: github/codeql-action/init@v1 47 | with: 48 | languages: ${{ matrix.language }} 49 | # If you wish to specify custom queries, you can do so here or in a config file. 50 | # By default, queries listed here will override any specified in a config file. 51 | # Prefix the list here with "+" to use these queries and those in the config file. 52 | # queries: ./path/to/local/query, your-org/your-repo/queries@main 53 | 54 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 55 | # If this step fails, then you should remove it and run the build manually (see below) 56 | - name: Autobuild 57 | uses: github/codeql-action/autobuild@v1 58 | 59 | # ℹ️ Command-line programs to run using the OS shell. 60 | # 📚 https://git.io/JvXDl 61 | 62 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines 63 | # and modify them (or add more) to build your code if your project 64 | # uses a compiled language 65 | 66 | #- run: | 67 | # make bootstrap 68 | # make release 69 | 70 | - name: Perform CodeQL Analysis 71 | uses: github/codeql-action/analyze@v1 72 | -------------------------------------------------------------------------------- /src/main/java/pdf/converter/img/ImgCreator.java: -------------------------------------------------------------------------------- 1 | package pdf.converter.img; 2 | 3 | import net.coobird.thumbnailator.Thumbnails; 4 | import org.apache.commons.io.FilenameUtils; 5 | import org.ghost4j.document.DocumentException; 6 | import org.ghost4j.document.PDFDocument; 7 | import org.ghost4j.renderer.RendererException; 8 | import org.ghost4j.renderer.SimpleRenderer; 9 | import org.slf4j.Logger; 10 | import org.slf4j.LoggerFactory; 11 | 12 | import javax.imageio.ImageIO; 13 | import java.awt.*; 14 | import java.awt.image.BufferedImage; 15 | import java.io.File; 16 | import java.io.IOException; 17 | 18 | public class ImgCreator { 19 | private static final Logger log = LoggerFactory.getLogger(ImgCreator.class); 20 | 21 | /** 22 | * @param pdf - File to be processed; 23 | * @param output - output directory, where images will be written; 24 | * @param resolution - output images resolution (usually 300+ for print quality, 72 for web); 25 | * @param extension - "png" or "jpg" 26 | * 27 | */ 28 | public void process(File pdf, File output, int resolution, int width, int height, ImageFileExtension extension){ 29 | PDFDocument document = new PDFDocument(); 30 | try { 31 | document.load(pdf); 32 | for(int page=0; page images = renderer.render(document, page, page); 36 | if(!images.isEmpty()){ 37 | persistImage(toBufferedImage(images.get(0)), width, height, new File(output, String.format("%05d.%s", page+1, extension.toString().toLowerCase()))); 38 | } 39 | } 40 | } catch (IOException |RendererException |DocumentException e) { 41 | log.warn(String.format("Failed to create images for document: %s", pdf.getName()), e); 42 | } 43 | } 44 | 45 | /* 46 | * Kudos to: http://stackoverflow.com/questions/13605248/java-converting-image-to-bufferedimage 47 | */ 48 | private BufferedImage toBufferedImage(Image img){ 49 | if (img instanceof BufferedImage){ 50 | return (BufferedImage) img; 51 | } 52 | // Create a buffered image with transparency 53 | BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); 54 | // Draw the image on to the buffered image 55 | Graphics2D bGr = bimage.createGraphics(); 56 | bGr.drawImage(img, 0, 0, null); 57 | bGr.dispose(); 58 | // Return the buffered image 59 | return bimage; 60 | } 61 | 62 | private void persistImage(BufferedImage image, int width, int height, File output) throws IOException { 63 | System.out.println(output); 64 | output.getParentFile().mkdirs(); 65 | ImageIO.write(Thumbnails.of(image).size(width, height).asBufferedImage(), FilenameUtils.getExtension(output.getAbsolutePath()), output); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/pdf/converter/PdfConverter.java: -------------------------------------------------------------------------------- 1 | package pdf.converter; 2 | 3 | import org.apache.commons.io.FileUtils; 4 | import pdf.converter.epub.EpubCreator; 5 | import pdf.converter.img.ImageFileExtension; 6 | import pdf.converter.img.ImgCreator; 7 | import pdf.converter.zip.ZipCreator; 8 | 9 | import java.io.File; 10 | import java.io.IOException; 11 | import java.nio.file.Files; 12 | import java.nio.file.Path; 13 | import java.util.UUID; 14 | 15 | public class PdfConverter { 16 | private static final int RESOLUTION = 300; 17 | private static final int WIDTH = 600; 18 | private static final int HEIGHT = 800; 19 | private File pdf; 20 | 21 | private PdfConverter(File pdf){ 22 | this.pdf = pdf; 23 | } 24 | 25 | public static PdfConverter convert(File pdf){ 26 | return new PdfConverter(pdf); 27 | } 28 | 29 | public void intoImage(File output, int resolution, int width, int height, ImageFileExtension format){ 30 | ImgCreator creator = new ImgCreator(); 31 | creator.process(pdf, output, resolution, width, height, format); 32 | } 33 | 34 | public void intoEpub(String title, File output){ 35 | try { 36 | //File imgsdir = File.createTempFile(UUID.randomUUID().toString(), ""); 37 | Path imgsdir = new File(String.format("/tmp/%s", UUID.randomUUID().toString())).toPath(); 38 | Files.createDirectories(imgsdir); 39 | 40 | 41 | ImgCreator creator = new ImgCreator(); 42 | creator.process(pdf, imgsdir.toFile(), RESOLUTION, WIDTH, HEIGHT, ImageFileExtension.PNG); 43 | EpubCreator epubCreator = new EpubCreator(); 44 | epubCreator.create(title, imgsdir.toFile(), output); 45 | FileUtils.deleteDirectory(imgsdir.toFile()); 46 | } catch (IOException e) { 47 | e.printStackTrace(); 48 | } 49 | 50 | } 51 | 52 | public void intoEpub(File imgsdir, String title, File output){ 53 | EpubCreator epubCreator = new EpubCreator(); 54 | try { 55 | epubCreator.create(title, imgsdir, output); 56 | } catch (IOException e) { 57 | e.printStackTrace(); 58 | } 59 | } 60 | 61 | public void intoZip(String title, File output){ 62 | try { 63 | File imgsdir = File.createTempFile(UUID.randomUUID().toString(), ""); 64 | imgsdir.mkdirs(); 65 | ImgCreator creator = new ImgCreator(); 66 | creator.process(pdf, imgsdir, RESOLUTION, WIDTH, HEIGHT, ImageFileExtension.PNG); 67 | ZipCreator zipCreator = new ZipCreator(); 68 | zipCreator.create(imgsdir, output); 69 | FileUtils.deleteDirectory(imgsdir); 70 | } catch (IOException e) { 71 | e.printStackTrace(); 72 | } 73 | 74 | } 75 | 76 | public void intoZip(File imgsdir, String title, File output){ 77 | ZipCreator zipCreator = new ZipCreator(); 78 | try { 79 | zipCreator.create(imgsdir, output); 80 | } catch (IOException e) { 81 | e.printStackTrace(); 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/pdf/converter/epub/EpubCreator.java: -------------------------------------------------------------------------------- 1 | package pdf.converter.epub; 2 | 3 | import com.google.common.collect.Lists; 4 | import org.apache.commons.io.FileUtils; 5 | import org.apache.commons.io.IOUtils; 6 | import org.joda.time.DateTime; 7 | import org.joda.time.format.DateTimeFormat; 8 | 9 | import java.io.*; 10 | import java.nio.file.Files; 11 | import java.nio.file.Path; 12 | import java.nio.file.Paths; 13 | import java.util.*; 14 | import java.util.zip.ZipEntry; 15 | import java.util.zip.ZipOutputStream; 16 | 17 | public class EpubCreator { 18 | private String timestamp; 19 | private String uuid; 20 | private File basedir; 21 | private ClassLoader classLoader; 22 | private String title; 23 | private File imgsDir; 24 | 25 | public void create(String title, File imgsDir, File output) throws IOException { 26 | timestamp = DateTimeFormat.forPattern("yyyy-MM-dd'T'hh:mm:ssSZZ").print(DateTime.now()); 27 | uuid = UUID.randomUUID().toString(); 28 | this.title = title; 29 | this.imgsDir = imgsDir; 30 | 31 | try { 32 | basedir = File.createTempFile(uuid,""); 33 | basedir.delete(); 34 | basedir.mkdirs(); 35 | } catch (IOException e) { 36 | e.printStackTrace(); 37 | } 38 | classLoader = getClass().getClassLoader(); 39 | 40 | copyImages(); 41 | copyStandardFilez(); 42 | createOPFFile(); 43 | createIndex(); 44 | createTitlePage(); 45 | createTOC(); 46 | pack(basedir.getAbsolutePath(), output.getAbsolutePath()); 47 | FileUtils.deleteDirectory(basedir); 48 | } 49 | 50 | private void copyImages() throws IOException { 51 | File imagesDir = new File(basedir, "images"); 52 | imagesDir.mkdirs(); 53 | for(File file : listFiles()){ 54 | try(FileInputStream fileInputStream = new FileInputStream(file); 55 | FileOutputStream fileOutputStream = new FileOutputStream(new File(imagesDir, file.getName()))) { 56 | IOUtils.copy(fileInputStream, fileOutputStream); 57 | } 58 | } 59 | } 60 | 61 | private void copyStandardFilez() throws IOException { 62 | File metainf = new File(basedir, "META-INF"); 63 | metainf.mkdirs(); 64 | writeFile(new File(metainf, "container.xml"), readFileFromSrc("epub/META-INF/container.xml")); 65 | 66 | writeFile(new File(basedir, "mimetype"), readFileFromSrc("epub/mimetype")); 67 | writeFile(new File(basedir, "page_styles.css"), readFileFromSrc("epub/page_styles.css")); 68 | writeFile(new File(basedir, "stylesheet.css"), readFileFromSrc("epub/stylesheet.css")); 69 | } 70 | 71 | private void createOPFFile() throws IOException { 72 | StringBuilder content = new StringBuilder(); 73 | for(File file : listFiles()){ 74 | content.append(String.format("\n", file.getName(), idForImage(file.getName()))); 75 | } 76 | String opf = readFileFromSrc("epub/content.opf"); 77 | opf = opf 78 | .replace("$AUTHOR", "Unknown") 79 | .replace("$TIMESTAMP", timestamp) 80 | .replace("$TITLE", title) 81 | .replace("$UUID", uuid) 82 | .replace("$CONTENT", content.toString()); 83 | 84 | writeFile(new File(basedir, "content.opf"), opf); 85 | } 86 | 87 | private void createIndex() throws IOException { 88 | StringBuilder content = new StringBuilder(); 89 | for(File file : listFiles()){ 90 | content.append(String.format("

\n", idForImage(file.getName()), file.getName())); 91 | } 92 | String index = readFileFromSrc("epub/index.html"); 93 | index = index.replace("$CONTENT", content.toString()); 94 | 95 | writeFile(new File(basedir, "index.html"), index); 96 | } 97 | 98 | private void createTitlePage() throws IOException { 99 | String pagetitle = readFileFromSrc("epub/titlepage.xhtml"); 100 | pagetitle = pagetitle.replace("$TITLE", title); 101 | 102 | writeFile(new File(basedir, "titlepage.xhtml"), pagetitle); 103 | } 104 | 105 | private void createTOC() throws IOException { 106 | String toc = readFileFromSrc("epub/toc.ncx"); 107 | toc = toc.replace("$TITLE", title); 108 | 109 | writeFile(new File(basedir, "toc.ncx"), toc); 110 | } 111 | 112 | private void writeFile(File dest, String content) throws IOException { 113 | FileWriter writer = new FileWriter(dest); 114 | writer.write(content); 115 | writer.flush(); 116 | writer.close(); 117 | } 118 | 119 | private String readFileFromSrc(String path) throws IOException { 120 | return IOUtils.toString(classLoader.getResourceAsStream(path)); 121 | } 122 | 123 | private String idForImage(String name){ 124 | return String.format("id%s", name.replace(".png", "")); 125 | } 126 | 127 | private static void pack(String sourceDirPath, String zipFilePath) throws IOException { 128 | Path p = Files.createFile(Paths.get(zipFilePath)); 129 | try (ZipOutputStream zs = new ZipOutputStream(Files.newOutputStream(p))) { 130 | Path pp = Paths.get(sourceDirPath); 131 | Files.walk(pp) 132 | .filter(path -> !Files.isDirectory(path)) 133 | .forEach(path -> { 134 | ZipEntry zipEntry = new ZipEntry(pp.relativize(path).toString()); 135 | try { 136 | zs.putNextEntry(zipEntry); 137 | zs.write(Files.readAllBytes(path)); 138 | zs.closeEntry(); 139 | } catch (Exception e) { 140 | System.err.println(e); 141 | } 142 | }); 143 | } 144 | } 145 | 146 | private List listFiles(){ 147 | File[] files = imgsDir.listFiles((dir, name) -> name.toLowerCase().endsWith(".png")); 148 | List sorted = Lists.newArrayList(files); 149 | sorted.sort(Comparator.comparing(File::toString)); 150 | return sorted; 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | 5 | 6 | org.sonatype.oss 7 | oss-parent 8 | 7 9 | 10 | 11 | com.bit-scout 12 | pdf-converter 13 | 1.0.3-SNAPSHOT 14 | 15 | pdf-converter 16 | A Java library to convert .pdf files into .txt, .jpg, .png, .epub and .zip formats. 17 | 18 | http://bit-scout.com 19 | 20 | 21 | 22 | Apache 2.0 23 | http://www.apache.org/licenses/LICENSE-2.0.html 24 | repo 25 | 26 | 27 | 28 | 29 | 30 | jmrozanec 31 | https://github.com/jmrozanec 32 | 33 | 34 | 35 | 36 | https://github.com/jmrozanec/pdf-converter/issues 37 | GitHub Issues 38 | 39 | 40 | 41 | https://github.com/jmrozanec/pdf-converter 42 | scm:git:git@github.com:jmrozanec/pdf-converter.git 43 | scm:git:git@github.com:jmrozanec/pdf-converter.git 44 | HEAD 45 | 46 | 47 | 48 | 49 | ossrh 50 | Release Repository 51 | https://oss.sonatype.org/service/local/staging/deploy/maven2/ 52 | 53 | 54 | ossrh 55 | Snapshots Repository 56 | https://oss.sonatype.org/content/repositories/snapshots/ 57 | 58 | 59 | 60 | 61 | 1.7.12 62 | 1.2.17 63 | 4.13.1 64 | 3.5.13 65 | 2.0.7 66 | 30.1.1-jre 67 | 68 | github 69 | UTF-8 70 | 71 | 72 | 73 | 74 | org.slf4j 75 | slf4j-api 76 | ${slf4j.version} 77 | 78 | 79 | joda-time 80 | joda-time 81 | 2.9.7 82 | 83 | 84 | org.apache.commons 85 | commons-lang3 86 | 3.5 87 | 88 | 89 | commons-io 90 | commons-io 91 | 2.7 92 | 93 | 94 | org.ghost4j 95 | ghost4j 96 | 1.0.0 97 | 98 | 99 | org.apache.pdfbox 100 | pdfbox 101 | 2.0.24 102 | 103 | 104 | org.apache.commons 105 | commons-exec 106 | 1.3 107 | 108 | 109 | com.google.guava 110 | guava 111 | ${guava.version} 112 | 113 | 114 | net.coobird 115 | thumbnailator 116 | 0.4.8 117 | 118 | 119 | 120 | org.slf4j 121 | slf4j-log4j12 122 | ${slf4j.version} 123 | test 124 | 125 | 126 | log4j 127 | log4j 128 | ${log4j.version} 129 | test 130 | 131 | 132 | junit 133 | junit 134 | ${junit.version} 135 | test 136 | 137 | 138 | org.mockito 139 | mockito-core 140 | ${mockito.version} 141 | test 142 | 143 | 144 | org.powermock 145 | powermock-module-junit4 146 | ${powermock.version} 147 | test 148 | 149 | 150 | org.powermock 151 | powermock-api-mockito2 152 | ${powermock.version} 153 | test 154 | 155 | 156 | 157 | 158 | 159 | 160 | maven-assembly-plugin 161 | 162 | 163 | 164 | 165 | 166 | 167 | jar-with-dependencies 168 | 169 | 170 | 171 | 172 | make-assembly 173 | package 174 | 175 | single 176 | 177 | 178 | 179 | 180 | 181 | org.apache.maven.plugins 182 | maven-compiler-plugin 183 | 3.1 184 | 185 | 1.8 186 | 1.8 187 | 188 | 189 | 190 | org.apache.maven.plugins 191 | maven-source-plugin 192 | 2.2.1 193 | 194 | 195 | attach-sources 196 | 197 | jar 198 | 199 | 200 | 201 | 202 | 203 | org.apache.maven.plugins 204 | maven-clean-plugin 205 | 2.5 206 | 207 | 208 | org.apache.maven.plugins 209 | maven-install-plugin 210 | 2.5.1 211 | 212 | 213 | org.apache.maven.plugins 214 | maven-jar-plugin 215 | 2.4 216 | 217 | 218 | org.apache.maven.plugins 219 | maven-resources-plugin 220 | 2.6 221 | 222 | 223 | org.apache.maven.plugins 224 | maven-javadoc-plugin 225 | 2.9.1 226 | 227 | 228 | attach-javadocs 229 | 230 | jar 231 | 232 | 233 | 234 | 235 | 236 | org.codehaus.mojo 237 | sonar-maven-plugin 238 | 1.0 239 | 240 | 241 | org.apache.maven.plugins 242 | maven-surefire-plugin 243 | 2.17 244 | 245 | 246 | org.apache.maven.plugins 247 | maven-deploy-plugin 248 | 2.8.1 249 | 250 | 251 | org.sonatype.plugins 252 | nexus-staging-maven-plugin 253 | 1.6.2 254 | true 255 | 256 | ossrh 257 | https://oss.sonatype.org/ 258 | true 259 | 260 | 261 | 262 | org.codehaus.mojo 263 | findbugs-maven-plugin 264 | 2.5.3 265 | 266 | 267 | org.codehaus.mojo 268 | clirr-maven-plugin 269 | 2.6.1 270 | 271 | 272 | org.codehaus.mojo 273 | versions-maven-plugin 274 | 2.1 275 | 276 | 277 | 278 | 279 | org.codehaus.mojo 280 | cobertura-maven-plugin 281 | 2.6 282 | 283 | xml 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | org.apache.maven.wagon 292 | wagon-webdav 293 | 1.0-beta-2 294 | 295 | 296 | 297 | 298 | 299 | 300 | release-sign-artifacts 301 | 302 | 303 | performRelease 304 | true 305 | 306 | 307 | 308 | 309 | 310 | org.apache.maven.plugins 311 | maven-gpg-plugin 312 | 1.5 313 | 314 | 315 | sign-artifacts 316 | verify 317 | 318 | sign 319 | 320 | 321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 | 329 | travis 330 | 331 | 332 | env.TRAVIS 333 | true 334 | 335 | 336 | 337 | 338 | 339 | org.eluder.coveralls 340 | coveralls-maven-plugin 341 | 2.2.0 342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | --------------------------------------------------------------------------------