Search code examples
jmeterperformance-testingload-testingbeanshell

JMeter Beanshell - save file as pdf


Currently I am saving variable values in ".txt" file using beanshell post-processor, I want to save variable value into a pdf file , is there any way I can achieve it?

To save variable value in a text file, i am using below code:

var1= vars.get("myVariableValue"); 

f = new FileOutputStream("D:/myTextFile.txt",true);
p = new PrintStream(f); 
this.interpreter.setOut(p); 
p.println(var1);

f.close();

Solution

    1. You need an external library like PdfBox for this
    2. You will need to have PDFBox in JMeter Classpath
    3. Since JMeter 3.1 you should be using JSR223 Test Elements and Groovy language for scripting

    Assuming all above:

    1. Download pdfbox-2.0.24.jar and fontbox-2.0.24.jar files and put them to "lib" folder of your JMeter installation

    2. Restart JMeter to pick up the "jar"

    3. Add an appropriate JSR223 Test Element to your Test Plan

    4. Put the following code into "Script" area:

      import org.apache.jmeter.threads.JMeterVariables
      
      JMeterVariables vars = new JMeterVariables()
      vars.put('myVariableValue','hello')
      
      def document = new org.apache.pdfbox.pdmodel.PDDocument()
      def page = new org.apache.pdfbox.pdmodel.PDPage()
      document.addPage(page)
      
      def contentStream = new org.apache.pdfbox.pdmodel.PDPageContentStream(document, page)
      
      contentStream.setFont(org.apache.pdfbox.pdmodel.font.PDType1Font.COURIER, 12)
      contentStream.beginText()
      contentStream.showText(vars.get('myVariableValue'))
      contentStream.endText()
      contentStream.close()
      
      document.save('myPDFFile.pdf')
      document.close()
      
    5. That's it, you should see myPDFFile.pdf file in JMeter's working directory