Search code examples
c++pdfmupdf

Create image annotation of pdf using MuPDF on Windows 8.1


I'm developing an WinRT application on C++ which should help users to read and annotate the PDF file. I'm using MuPDF to parse the PDF. I'm able to read the PDF and add lines and free text annotations but unable to insert an image to page. I couldn't find any sample nor could I find any manuals that explains what I am looking for. I'm using the following code to create an image but image isn't appearing:

std::string pathToOutputBook3 += "\\testPDF.pdf";
std::string pathToImage3 = "Assets/hortitsa.jpg";

fz_point pts[4] = { { 0, 0 }, { 0, 0 }, { 600, 0 }, { 600, 499 } };
fz_rect rect = fz_empty_rect;
pdf_document *pdfDoc = (pdf_document *)this->mu_doc;
pdf_page *pdfPage = (pdf_page *)page;
image_document *imgDoc = (image_document *)fz_open_document(this->mu_ctx, pathToImage3.c_str());
fz_image *image = imgDoc->image;
fz_matrix page_ctm = { 1, 0, 0, 1, 0, 0 };

fz_include_point_in_rect(&rect, &pts[0]);
fz_include_point_in_rect(&rect, &pts[1]);
fz_include_point_in_rect(&rect, &pts[2]);
fz_include_point_in_rect(&rect, &pts[3]);

display_list = fz_new_display_list(this->mu_ctx);
dev = fz_new_list_device(this->mu_ctx, display_list);

auto annot = pdf_create_annot(pdfDoc, pdfPage, fz_annot_type::FZ_ANNOT_SQUARE);

fz_fill_image(dev, image, &page_ctm, 1.0f);

fz_transform_rect(&rect, &page_ctm);
pdf_set_annot_appearance(pdfDoc, annot, &rect, display_list);

fz_write_document(this->mu_doc, (char *)pathToOutputBook3.c_str(), nullptr);

Solution

  • There is no 'image' annotation type. There are annotation types which might be abused to store an image in the appearance, but readers which ignore the appearance stream and create new ones from the annotation dictionary (eg Adobe Acrobat) will still not display the image.

    If you want to add an image to a document then you need to do that, not try to use an annotation. I believe it is now possible to add an image to the page contents stream using MuPDF, but I don't know how to do that myself.