I have written a code to generate bar codes and saved them to a pdf file . The code executes successfylly but the PDF file does not open saying giving an error whome picture I am uploading. Please see my code and Picture with the error.

barcodeError.PNG

 public void createPDF(String pdfFileName,String myString) throws FileNotFoundException{
        Document doc = new Document() ;
        PdfWriter docwriter = null;

        try{
            docwriter = PdfWriter.getInstance(doc, new FileOutputStream("C:\\Users\\hp430\\Desktop\\barcodes\\"+pdfFileName));
            doc.addAuthor("Saboor Siddique");
            doc.addCreationDate();
            doc.addProducer();
            doc.addCreator("SunSoftTechnologies");
            doc.addTitle("Barcode Test");
            doc.setPageSize(PageSize.LETTER);
            doc.open();

            PdfContentByte cb= docwriter.getDirectContent();

            Barcode128 code128 = new Barcode128();
            code128.setCode(myString.trim());
            code128.setCodeType(Barcode128.CODE128);
            code128.setBarHeight(5f);
            code128.setX(0.1f);

            Image code128Image = code128.createImageWithBarcode(cb, null, null);
            code128Image.setAbsolutePosition(10, 700);
            code128Image.scalePercent(125);
            doc.add(code128Image);

        }
        catch(DocumentException dex){
            System.out.println(dex);
        }
    }

maybe you need to flush/close the output stream explicitly?

commented: Thanks for your response James. I forgot to flush out the streams. I did that and now the pdf is not crashing +3

Thanx James. I flushed out and closed the streams and the problem is solved.

I worked out from FileNotFoundException that your code is written in Java.
So I am assuming you added towards end:
doc.close();
or the file would have been corrupted or assumed Java would auto-close your file on exit which maybe it didn't since file was corrupted and not flushed out from buffer to disk as above person said.
In https://www.programcreek.com/java-api-examples/?api=com.itextpdf.text.pdf.PdfWriter it shows doc.close() after doc.add().

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.