0

I would like to merge multiples pdf into a new pdf and add stationery on each page.

For that I used PdfWriter like this :

public class FusionPdf extends PdfPageEventHelper {

private Document document = null;
private PdfWriter writer = null;
private PdfReader markReader = null;
private PdfImportedPage fondDePage = null;
private String textFili = null;
private String textMark = null;
private static final Font FONT1 = FontFactory.getFont(FontFactory.HELVETICA, 50, Font.NORMAL, new GrayColor(0.7f));
private static final Font FONT2 = FontFactory.getFont(FontFactory.HELVETICA, 6, Font.NORMAL, BaseColor.BLACK);

/**
 * liste des fichiers � concatener
 */
private List<File> pdfsOriginaux = new ArrayList<File>();

/**
 * 
 * @param pdfDestination fichier de pdf de destination
 * @param pdfsOriginaux fichiers pdf � concatener
 * @param pdfTatoueur Fond de page (peut �tre null)
 * @param textFiligrane filigran (peut �tre null)
 * @throws IOException 
 * @throws DocumentException 
 * @throws Exception
 */

public FusionPdf(File pdfDestination, List<File> pdfsOriginaux, File pdfTatoueur, String textFiligrane, String textMarquage) throws DocumentException, IOException  {
    if (pdfsOriginaux.isEmpty()){
        throw new IOException("Aucun document pdf a traiter !");
    }
    this.pdfsOriginaux = pdfsOriginaux;
    this.init(pdfDestination, pdfTatoueur, textFiligrane, textMarquage);
}

/**
 * 
 * @param pdfDestination fichier de pdf de destination
 * @param pdfOriginal fichier pdf a traiter
 * @param pdfTatoueur Fond de page (peut etre null)
 * @param textFiligrane filigrane (peut etre null)
 * @param textMarquage note technique en haut à droite en petit (peut etre null)
 * @throws IOException
 * @throws DocumentException
 * @throws Exception
 */

public FusionPdf(File pdfDestination, File pdfOriginal, File pdfTatoueur, String textFiligrane, String textMarquage) throws DocumentException, IOException  {
    this.pdfsOriginaux.add(pdfOriginal);
    this.init(pdfDestination, pdfTatoueur, textFiligrane, textMarquage);
}

/**
 * initialisation des attributs
 * 
 * @param pdfDestination
 * @param pdfTatoueur
 * @param textFiligrane
 * @throws DocumentException
 * @throws IOException
 */

private void init(File pdfDestination, File pdfTatoueur, String textFiligrane, String textMarquage) throws DocumentException, IOException{

    document = new Document();
    writer = PdfWriter.getInstance(document, new FileOutputStream(pdfDestination));
    writer.setPageEvent(this);
    if (pdfTatoueur != null) {
        markReader = new PdfReader(pdfTatoueur.getAbsolutePath());
        fondDePage = writer.getImportedPage(markReader, 1);
    }

    if (textFiligrane != null) {
        textFili = textFiligrane;
    }

    if (textFiligrane != null) {
        textMark = textMarquage;
    }

}

/**
 * applique la concatenation et la fusion
 * @throws IOException
 */
public void fuse() throws IOException{
    //---->initialisation d'un flux vers le pdf
    PdfReader originalReader = new PdfReader(pdfsOriginaux.get(0).getAbsolutePath());
    document.open();

    for (File pdfOriginal : pdfsOriginaux) {
        originalReader = new PdfReader(pdfOriginal.getAbsolutePath());
        for (int i = 1; i <= originalReader.getNumberOfPages(); i++) {
                document.setPageSize(originalReader.getPageSizeWithRotation(i));
                document.newPage();
                writer.getDirectContent().addTemplate(writer.getImportedPage(originalReader, i), 0, 0);
        }
    }
    document.close();
    originalReader.close();
    if (markReader != null) {
        markReader.close();
    }
}


@Override
public void onEndPage(PdfWriter writer, Document document) {
    PdfContentByte directContent;
    Rectangle docPageSize = document.getPageSize();

    //ajout du fond de page
    if (markReader != null) {
        directContent = writer.getDirectContentUnder();
        Rectangle markPageSize = markReader.getPageSize(1);
        float hScale = docPageSize.getWidth() / markPageSize.getWidth();
        float vScale = docPageSize.getHeight() / markPageSize.getHeight();
        float markScale = (hScale< vScale) ? hScale :  vScale;
        float hTrans = (float)((docPageSize.getWidth()-markPageSize.getWidth()* markScale) / 2.0);
        float vTrans = (float)((docPageSize.getHeight()-markPageSize.getHeight()* markScale) / 2.0);
        directContent.addTemplate(fondDePage, markScale, 0, 0, markScale, hTrans, vTrans );    
    }

    //ajout du filigrane
    if (textFili != null) {
        directContent = writer.getDirectContent();
        PdfGState gstate = new PdfGState();
        gstate.setFillOpacity(0.3f);
        gstate.setStrokeOpacity(0.3f);
        directContent.saveState();
        directContent.setGState(gstate);
        ColumnText.showTextAligned(directContent,Element.ALIGN_CENTER, new Phrase(textFili, FONT1), docPageSize.getWidth()/2, docPageSize.getHeight()/2, 45);
        directContent.restoreState();
    }

    //ajout de la marque en haut à droite en petit
    if (textMark != null) {
        directContent = writer.getDirectContent();
        PdfGState gstate = new PdfGState();
        directContent.saveState();
        directContent.setGState(gstate);
        ColumnText.showTextAligned(directContent,Element.ALIGN_RIGHT, new Phrase(textMark, FONT2), docPageSize.getWidth()-3, docPageSize.getHeight()-8, 0);
        directContent.restoreState();
    }
}

}

But this was wrong : depending of original pdf the result was sometime buggy. The orientation was not keept. Then I found the answer of that behavior here function that can use iText to concatenate / merge pdfs together - causing some issues

=> According to M. Lowagie I have to use PdfCopy instead of PdfWriter. Then I made this code:

public class FusionPdf2 extends PdfPageEventHelper {

private static final Font FONT1 = FontFactory.getFont(FontFactory.HELVETICA, 50, Font.NORMAL, new GrayColor(0.7f));
private static final Font FONT2 = FontFactory.getFont(FontFactory.HELVETICA, 6, Font.NORMAL, BaseColor.BLACK);

private List<File> pdfsOriginaux = new ArrayList<File>();
private File pdfDestination = null;
private File pdfTatoueur = null;
private String textFiligrane = null;
private String textMarquage = null;


/**
 * 
 * @param pdfDestination fichier de pdf de destination
 * @param pdfsOriginaux fichiers pdf à concatener
 * @param pdfTatoueur Fond de page (peut être null)
 * @param textFiligrane filigran (peut être null)
 * @throws IOException 
 * @throws DocumentException 
 * @throws Exception
 */
public FusionPdf2(File pdfDestination, List<File> pdfsOriginaux, File pdfTatoueur, String textFiligrane, String textMarquage) throws DocumentException, IOException  {
    this.pdfDestination = pdfDestination;
    if (pdfsOriginaux.isEmpty()){
        throw new IOException("Aucun document pdf a traiter !");
    }
    this.pdfsOriginaux = pdfsOriginaux;
    this.pdfTatoueur = pdfTatoueur;
    this.textFiligrane = textFiligrane;
    this.textMarquage = textMarquage;
}


/**
 * 
 * @param pdfDestination fichier de pdf de destination
 * @param pdfOriginal fichier pdf a traiter
 * @param pdfTatoueur Fond de page (peut etre null)
 * @param textFiligrane filigrane (peut etre null)
 * @param textMarquage note technique en haut à droite en petit (peut etre null)
 * @throws IOException
 * @throws DocumentException
 * @throws Exception
 */
public FusionPdf2(File pdfDestination, File pdfOriginal, File pdfTatoueur, String textFiligrane, String textMarquage) throws DocumentException, IOException  {
    this.pdfDestination = pdfDestination;
    this.pdfsOriginaux.add(pdfOriginal);
    this.pdfTatoueur = pdfTatoueur;
    this.textFiligrane = textFiligrane;
    this.textMarquage = textMarquage;
}

/**
 * applique la concatenation et la fusion
 * 
 * @param pdfDestination
 * @param pdfTatoueur
 * @param textFiligrane
 * @throws DocumentException
 * @throws IOException
 * @throws IOException
 * @throws DocumentException 
 */
public void fuse() throws IOException, DocumentException{

    Document document = new Document();
    PdfCopy copy = new PdfCopy(document, new FileOutputStream(pdfDestination));
    document.open();
    PdfReader originalReader;
    PdfReader fdpReader = null;

    if (pdfTatoueur != null) {
        fdpReader = new PdfReader(pdfTatoueur.getAbsolutePath());
    }

    for (File pdfOriginal : pdfsOriginaux) {
        originalReader = new PdfReader(pdfOriginal.getAbsolutePath());
        for (int i = 0 ; i < originalReader.getNumberOfPages(); ) {
            PdfImportedPage page = copy.getImportedPage(originalReader, ++i);
            PageStamp stamp = copy.createPageStamp(page);
            Rectangle docPageSize = originalReader.getPageSizeWithRotation(i);

            //ajout du fond de page
            if (pdfTatoueur != null) {

                PdfImportedPage fondDePage = copy.getImportedPage(fdpReader, 1);

                PdfContentByte directContent = stamp.getUnderContent();
                Rectangle markPageSize = fdpReader.getPageSize(1);
                float hScale = docPageSize.getWidth() / markPageSize.getWidth();
                float vScale = docPageSize.getHeight() / markPageSize.getHeight();
                float markScale = (hScale< vScale) ? hScale :  vScale;
                float hTrans = (float)((docPageSize.getWidth()-markPageSize.getWidth()* markScale) / 2.0);
                float vTrans = (float)((docPageSize.getHeight()-markPageSize.getHeight()* markScale) / 2.0);
                directContent.addTemplate(fondDePage, markScale, 0, 0, markScale, hTrans, vTrans );
            }

            //ajout du filigrane
            if (StringUtils.isNotBlank(textFiligrane)) {
                PdfContentByte directContent = stamp.getOverContent();
                PdfGState gstate = new PdfGState();
                gstate.setFillOpacity(0.3f);
                gstate.setStrokeOpacity(0.3f);
                directContent.saveState();
                directContent.setGState(gstate);
                ColumnText.showTextAligned(directContent,Element.ALIGN_CENTER, new Phrase(textFiligrane, FONT1), docPageSize.getWidth()/2, docPageSize.getHeight()/2, 45);
                directContent.restoreState();
            }

            //ajout de la marque en haut à droite en petit
            if (StringUtils.isNotBlank(textMarquage)) {
                PdfContentByte directContent = stamp.getOverContent();
                ColumnText.showTextAligned(directContent,Element.ALIGN_RIGHT, new Phrase(textMarquage, FONT2), docPageSize.getWidth()-3, docPageSize.getHeight()-8, 0);
            }

            stamp.alterContents();
            copy.addPage(page);
        }

        if (originalReader!=null) {
            originalReader.close();
        }
    }

    document.close();        

}

}

This time the result is good in any case : all page are in the good orientation.

BUT the producted pdf is about 10 times fater than with the previous code. After analysing I found out the cause : all was good until I added the stationery.

It is like the content of the stationery is duplicated for each page instead of being reused.

Obviously I did it wrong again. I read all the chapter 6 of the book wihtout finding the solution.

If anyone can help me!

Community
  • 1
  • 1
SylvainP
  • 23
  • 4
  • 1
    *"It is like the content of the stationery is duplicated for each page instead of being reused"* - this is exactly the difference in code: in your code using `PdfWriter` you use `getImportedPage(markReader, 1)` only once, in your code using `PdfCopy` you call `getImportedPage(fdpReader, 1)` for each page. – mkl Nov 11 '16 at 05:27
  • I'd make that an answer @mkl – Bruno Lowagie Nov 11 '16 at 07:17
  • @Bruno I'm going to. When I wrote the comment I was online via smartphone, and writing complete answers here on such devices is quite a pain. – mkl Nov 11 '16 at 07:32

1 Answers1

0

It is like the content of the stationery is duplicated for each page instead of being reused.

This is true and it reflects a fundamental difference between your FusionPdf and FusionPdf2 classes:

In the former class you import the stationary page once at the beginning

private void init(File pdfDestination, File pdfTatoueur, String textFiligrane, String textMarquage) throws DocumentException, IOException{
    [...]
    if (pdfTatoueur != null) {
        markReader = new PdfReader(pdfTatoueur.getAbsolutePath());
        fondDePage = writer.getImportedPage(markReader, 1);
    }
    [...]
}

and reuse this imported page again and again:

public void onEndPage(PdfWriter writer, Document document) {
    [...]

    //ajout du fond de page
    if (markReader != null) {
        [...]
        directContent.addTemplate(fondDePage, markScale, 0, 0, markScale, hTrans, vTrans );    
    }

    [...]
}

In the latter class, on the other hand, you import the stationary page again and again, once per page it is applied to:

for (int i = 0 ; i < originalReader.getNumberOfPages(); ) {
    [...]
    if (pdfTatoueur != null) {

        PdfImportedPage fondDePage = copy.getImportedPage(fdpReader, 1);

        [...]
        directContent.addTemplate(fondDePage, markScale, 0, 0, markScale, hTrans, vTrans );
    }

    [...]
}

To have the contents of the stationary page in the result PDF only once, you need to import it only once.

mkl
  • 90,588
  • 15
  • 125
  • 265
  • I hesitate between : "shame on me", "laaaame" and "dumb-ass" .. It will teach me to drop a dev unfinished... Anyway thank you for your help! – SylvainP Nov 15 '16 at 17:25
  • @SylvainP If the answer helped you, please accept it (click the tick at its left). – mkl Nov 15 '16 at 17:33