Search code examples
c#pdfitextwmf

How to convert/add .wmf to .pdf


Ive got this sample code but Iam not getting it working. My question is how to convert/add a .wmf file into a PDF.

private void CreatePDF()
    {
        Document pdfDoc = new Document();
        PdfWriter.GetInstance(pdfDoc, new FileStream(@"path.pdf", FileMode.Create));

        byte[] b =  File.ReadAllBytes(@"path.wmf");

        iTextSharp.text.Image img1 = new ImgWMF(b);
        pdfDoc.Add(img1);
        pdfDoc.Close();
    }

Iam trying to read the bytes out of the .wmf and create a image with that, trying to add that to the PDF creator afterwards.

Iam not able to read out the bytes that way I guess. Any help appreciated.

Kindly Regards, ChekaZ


Solution

  • You don't need to use the ImgWMF class; and your code doesn't work because you skipped a step: you're not opening the pdfDoc.

    I'm not a C# developer, but this is how I would (try to) fix your code:

    Document pdfDoc = new Document();
    PdfWriter.GetInstance(pdfDoc, new FileStream(@"path.pdf", FileMode.Create));
    pdfDoc.Open();
    iTextSharp.text.Image img1 = ImgWMF.GetInstance(@"path.wmf");
    pdfDoc.Add(img1);
    pdfDoc.Close();
    

    The GetInstance() method examines the image file you pass as a parameter. If this doesn't work, please share the exception that is thrown.

    Note that your PDF page will be of size A4, and your image might not fit (or the page may be too big). In that case, you should create your image first, and create your PDF like this:

    iTextSharp.text.Image img1 = ImgWMF.GetInstance(@"path.wmf");
    Document pdfDoc = new Document(img1);
    PdfWriter.GetInstance(pdfDoc, new FileStream(@"path.pdf", FileMode.Create));
    pdfDoc.Open();
    img1.SetAbsolutePosition(0, 0);
    pdfDoc.Add(img1);
    pdfDoc.Close();