title: MailMerge and Convert Docx to PDF using Apache-POI - Java
body: <p>I have a docx file which has merge fields. It incorporates an xls file to generate multiple records. Each record in docx is linked to a record in xls file. When I convert this docx to pdf using apache poi, it converts the first record ONLY. How to convert all the records?
  Here is what I did:</p>
  
  <pre><code>import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
  import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
  import java.io.File;
  import java.io.FileInputStream;
  import java.io.FileNotFoundException;
  import java.io.FileOutputStream;
  import java.io.IOException;
  import java.io.InputStream;
  import java.io.OutputStream;
  import org.apache.poi.xwpf.usermodel.XWPFDocument;
  
  public class Doc2PDF {
  
      /**
       * @param args the command line arguments
       */
      public static final String SOURCE_DOCX = "N:\\HSV_Letter1.docx";
      public static final String TARGET_PDF = "N:\\HSV.pdf";
  
      public static void main(String[] args) {
          // TODO code application logic here
          Doc2PDF cwoWord = new Doc2PDF();
          System.out.println("Start");
          cwoWord.ConvertToPDF(SOURCE_DOCX, TARGET_PDF);
  
      }
  
      public void ConvertToPDF(String docPath, String pdfPath) {
          try {
              InputStream doc = new FileInputStream(new File(docPath));
  //            XWPFDocument document = new XWPFDocument(new File(docPath).toURI().toURL().openStream());
              XWPFDocument document = new XWPFDocument(doc);
              PdfOptions options = PdfOptions.create();
              OutputStream out = new FileOutputStream(new File(pdfPath));
              PdfConverter.getInstance().convert(document, out, options);
              System.out.println("Done");
          } catch (FileNotFoundException ex) {
              System.out.println(ex.getMessage());
          } catch (IOException ex) {
  
              System.out.println(ex.getMessage());
          }
      }
  
  }
  </code></pre>