c# - How can I embed any file type into Microsoft Word without interop assemblies -
i'm trying how can embed file type microsoft word using openxml 2.0
but using openxml sdk 2.5 (no interop assemblies )
i can embed other word (or office) files using following code sample here
(we need add reference documentformat.openxml nuget , windowsbase)
but i'm having trouble refactoring accept file type (pdf ,mp3 etc)
using documentformat.openxml.packaging; using documentformat.openxml.wordprocessing; using documentformat.openxml; using v = documentformat.openxml.vml; using ovml = documentformat.openxml.vml.office; using system.io; class program { static void main(string[] args) { //just update following 2 variables point existng files string containingdocumentpath = @"c:\temp\word\containingdocument.docx"; string embeddeddocumentpath = @"c:\temp\word\embeddeddocument.docx"; createpackage(containingdocumentpath, embeddeddocumentpath); } private static void createpackage(string containingdocumentpath, string embeddeddocumentpath) { using (wordprocessingdocument package = wordprocessingdocument.create(containingdocumentpath, wordprocessingdocumenttype.document)) { addparts(package, embeddeddocumentpath); } } private static void addparts(wordprocessingdocument parent, string embeddeddocumentpath) { var maindocumentpart = parent.addmaindocumentpart(); generatemaindocumentpart().save(maindocumentpart); var embeddedpackagepart = maindocumentpart.addnewpart<embeddedpackagepart>("application/vnd.openxmlformats-" + "officedocument.wordprocessingml.document", "rid1"); generateembeddedpackagepart(embeddedpackagepart, embeddeddocumentpath); var imagepart = maindocumentpart.addnewpart<imagepart>("image/x-emf", "rid2"); generateimagepart(imagepart); } private static document generatemaindocumentpart() { var element = new document( new body( new paragraph( new run( new text( "this containing document."))), new paragraph( new run( new text( "this embedded document: "))), new paragraph( new run( new embeddedobject( new v.shape( new v.imagedata() { title = "", relationshipid = "rid2" } ) { id = "_x0000_i1025", style = "width:76.5pt;height:49.5pt", ole = truefalseblankvalue.fromboolean(false)//v.booleanentrywithblankvalues.empty }, new ovml.oleobject() { type = ovml.olevalues.embed, progid = "word.document.12", shapeid = "_x0000_i1025", drawaspect = ovml.oledrawaspectvalues.icon, objectid = "_1299573545", id = "rid1" } ) //{ // dxaoriginal = (uint32value)1531ul, // dyaoriginal = (uint32value)991ul //} ) ) ) ); return element; } public static void generateembeddedpackagepart(openxmlpart part, string embeddeddocumentpath) { byte[] embeddeddocumentbytes; // following code generate exception if invalid // filename passed. using (filestream fsembeddeddocument = file.openread(embeddeddocumentpath)) { embeddeddocumentbytes = new byte[fsembeddeddocument.length]; fsembeddeddocument.read(embeddeddocumentbytes, 0, embeddeddocumentbytes.length); } using (binarywriter writer = new binarywriter(part.getstream())) { writer.write(embeddeddocumentbytes); writer.flush(); } } public static void generateimagepart(openxmlpart part) { #region icon bytes // best practice icon should stored resource // in assembly instead of base64 string. string iconbytes = @" aqaaagwaaaaaaaaaaqaaagqaaaauaaaaaaaaaaaaaaaodgaagakaacbftuyaaaeabbq aabaaaaacaaaaaaaaaaaaaaaaaaaaqayaalaeaaa0agaapweaaaaaaaaaaaaaaaaaan yccacldqyagaaaaawaaaaaaaaagqaaaawaaad///8acgaaakaqaaajaaaaaqaaaeiaa aagaaaaiwaaaaeaaaagaaaaiaaaaaca/weaaaaaaaaaaaaagd8aaaaaaaaaaaaagd8a aaaaaaaaap///waaaaaabaaaadqaaacgaaaaabaaacaaaaagaaaakaaaacaaaaagaaa aaqagaamaaaaaeaaaaaaaaaaaaaaaaaaaaaaaaaaa/waa/waa/waaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaauasv/5f8av9 4yuz/alm8/2zon/9isjl/yegw/2bimp9gsdd/yegw/2bimp9gsdd/yegw/2bimp9gsd d/yegw/2bimp9gsdd/yegw/2bimp9gsdd/yegw/2bimp9gsdd/yegw/waaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaac6pzb//orf/9/nxp/dxbf/3r2s/964ov/jspj/5boq /+wzkp/ls5d/5bko/+awi//nr4j/6a2f/+qsgv/rqn//7kd7/+6ld//vo3p/8afv//g ga//znmj/851l//sby/9gsdd/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaalqllv /86+h//ovh//zr4f/86+d/++rf//vp3//76d7/++nd//ro3p/759z/+uba//rm2f/65 df/+utw//rj1p/64tp/+eds//ngz//53s7/+d3m//ncyv/528j/9jxl/2bimp8aaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaau6ax//zu5p/77et//o3k//vs5p/77op//ov i//vr4v/76+d/++rf//vp3//76d3/++jc//rn2v/65tr/+uty//rk1v/54tt/+uht// rg0f/538//+d7n//ncyv/znwf/yegw/waaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ac7p5j//o/n//zv5//77+b//o/m//zv5v/87ex//o3k//zt5p/87op//ovi//zq4f/8 6t//++re//vo3p/759v/+uba//rl1//65nx/+ult//nh0f/64nd/+t/o//keav9gsdd /aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaalyomp/88er//php//zx6v/88on//p dp//zw6p/97+j//o/n//zu5v/87ux//o3k//zs4//87oh/06ml/9koif/rpof/0awg/ 9ckhp/po4p/+upv//rh0v/64nd/8abt/2bimp8aaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaavama//3z7f/98+3//fps//3y7p/98+v//flr//zy6v/98er//fhp//zw6p/ 87+f//o7m//zt5p/87ep//ovh//vq3//76d3/++jc//rm2f/65nf/+upw//ri0//won d/yegw/waaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaac+qpv//fxv//307//jwaj/4 r+l/+g9o//fu6h/3rme/923np/btzr/2rox/9mxlf/ysjp/166r/9asj//vq43/1kml /9koif/spoj/0awg//vn2v/65dj/+upw/++jc/9gsdd/aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaal+rnp/+9vh//fbx//328f/99vh//fbx//718p/99fd//fxw//307/ /98+7//fpt//3y7p/88er//pdp//zv5//87ux//o3k//zr4v/86t//++jd//vn2v/65 dj/7av3/2bimp8aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaawkye//348//99/p/ 5swt/+xdq//jwaj/4b6l/+c8ov/euqd/3rmf/923np/ctpr/2rsy/9mylv/ysjp/166 r/9atj//vq43/1kql/9ooiv/76ud/++nd//vn2//tp3v/yegw/waaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaadbrp7//vn1//759f/++fx//vj1//749f/++px//vj1//339 p/+9/p//vfz//338v/99vh//fxw//307v/98+3//plr//zx6f/87+f//o7k//vs4v/7 6ud/++jd/+upf/9gsdd/aaaaaaaaaaaaaaaaaaaaaaaaaaeaaaaaaaaaamkun//++vf //vr3/+jjsf/nx6//5swt/+xdq//jwqj/4scm/+g+pp/gvkh/3rqf/924np/ctpr/2r sy/9mylv/ysjt/166r/9atj//vq47//o7l//zs4//76t//6aud/2bimp8aaaaaaaaaa aaaaaaaaaabaaaabqaaaa0aaaaurpyp/9/c2f/b2nx/1dho/9dlyv/jxcp/xcg//8rg xp/oysj/8ezp//v28//9+px//vj1//749p/+9/p//fbx//318p/99o3//flr//zx6f/ 87+f//o3k//zs4v/orof/yegw/waaaaaaaaaaaaaaaqaaaamaaaaoaaaaigaaadwqgx b/tlgv/62rqf+tfgv/min0/6kqgv+3p5n/yrus/8ksmf+6oy//3bqh/+c9o//gvkl/3 rqf/924nf/ctpv/27sy/9mylv/ysjt/16+s//zx6f/97+f//o3k/+avi/9gsdd/aaaa aaaaaabuosxaczwnzww4jnf5vebekhpw6q+dlv/full/3tbs//xx7p/8+pp/+/bv//n 06//48uf/vqmb/9jw1p/r6ob//fr4//77+f/++vj//vn2//749f/99/p//fbx//307/ /98+3//flr//3w6p/87ub/5bgp/2bimp8aaaaaaaaaaixlmpdeuar/vpql/9gmlf/// //////////////+/vz//vz6//369v/8+pp/+/bv//n06//bqpz/v6oo/9kznp/jwaj/ 4scn/+g+pp/gvkl/37qg/924nf/ctpv/27sy/9qzlv/98+3//phq//zw6p/ls5l/yeg w/waaaaaaaaaajk0z8nq2qf+xclj/0720///////68vd/6ms9///////z4t3/2z6t// 369v/8+pp/+/bv/828sp/u0tl/6+no//78+//+/pv//vz6//77+f/++vj//vn2//749 p/99/p//fbx//307v/98u3//fhq/+s1lv9gsdd/aaaaaaaaaacqudbw2bwm/6rtmf+4 jxv///////nx7/+3xex/9+3q//hg3p+zvdv/7ntn//369v/8+pp/2mvb/9hpz//q6oj //vz8///9/p/ooyh/zqgb/86hgf/ooyh/zqgb/86hgf/ooyh//vxw//307v/98uz/4r ea/2bimp8aaaaaaaaaajjsofdytkt/ok8s/6rot////////v38/6rhj/+/fwf/79/z/ 6dnl/+5cln//pj1//369v/j2nh/z87n/+no5//+/fz///38//pkqv/mvql/58on/+e/ pp/is5p/5lax/86hgf/+9vh//ftv//3z7f/huzz/yegw/waaaaaaaaaalfu88nizpf+ ityz/keum////////////n0gk/8wqev/il4p/oeon/9wwop/ooo///vz6//dq5f/my8 v/6ofn//79/f///v3/88qq/9mpip/fspl/5bmb/+cxkv/kt5n/zqgb//728v/99vd// fpu/+g6n/9gsdd/aaaaaaaaaacwwd/w2lsl/6rplf+lorb/8evp//////+lvtp/6dbo /7frtv+fssb//v38/69nsf/v4dn/+/j2/8niyp/m5ex//fz8///+/f/zyqr/6cgl/+j dqp/mvql/3q+o/+o4mf/ooyh//vfz//328f/99e//37uh/2bimp8aaaaaaaaaajlbqf dmy8h/x451/7f3x//h1c//+/j3/6zxnv/vskd/7+hc/6zxnv//////wyly/7yaz//+/ vz/y8rk/+xk5p/9/pz///79//pkqv/049f/7njk//v18p/kwqr/48gn/+k/pf/eu6x/ 3rul/967pf/fvkp/yegw/waaaaaaaaaam15e8onqx//pmox/vyzx/9bcuv/59ph/69j r/+zb1p/////////////////////////////////r0nd/5etk//z7+////v3/88qq// 359v/+/f3/69fj/76snf+mdmp/ihje/4frv/96y07/cltf/2ptpp9gsdd/aaaaaaaaa acvxepk59dg/9eql//ilh//z7oo//////////////////////////////////////// /////////+df3//p6oj//fz8///+/f/zyqr///////v07//049f/v62d/+zsv//qzrv /58q1/+terv/hvqn/yegw/yukjckaaaaaaaaaag1em6xvskh/8n3w/9sij//vsal/// ////////////////////38/p/x6ex/8+zq//tv7v/cysl/9ppz//v6+v/+/f3///7+/ /pkqv/zyqr/88qq//pkqv/brp///+7k//vo3p/03td/7ttd/2bimp8ljcqpgbgxggaa aaaaaaaaibqpmkhrufzkyl7/8uda/9kllp/spzt/0qwu/9wol//xqzj/16my/9iqmp/ spzt/0qwu/7webv/8+/v//v39///+/v///v7///79//7+/f///fz///37/8kwop//7u t/++jc//xe0p9ltjb/jsqkkrgyfxoaaaaaaaaaaaaaaaaaaaaaqskgykzruvburp//9 exf//tk3v/05n7/9ote//xl3//15d//9exf//xl3//15d//u4hz//79/f///v7///7+ ///+/v///v3///39///9/p///fv/xlkj///u5p/76nz/bfu+/yukjckygbcaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaafg4lixfjokwczu3kr3jx/69yv/+vclf/r3jx/69yv/ +vclf/r3jx/69yv/+9i3t///7+///+/v///v7///7+///+/v///v3///39///9/p/gt kt//+7k/4nuwf8ljcqpgbgxggaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaadrv7h//////////////////////////////////////////////////// ////+/v////7///7+///+/v///f3///38/8i1pf+chnt/jsqkkrgyfxoaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaang/sf/rv7h/0b+x/9g/s f/qvrd/z72v/8+9r//pvk7/zbut/827rp/nuaz/zlmr/8u4qv/kt6n/yreo/8m2p//i tqf/ybam/yukjckxfxczaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaayaaaadaaaaaaaaaisaaaadaaaaaeaaabsaaaacaeaaaea aad1////aaaaaaaaaaaaaaaakaeaaaaaaaaaqaaivabhaggabwbtageaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaat310cq aa3lmcwf//aady4qaaaabkwczmmadasrnzaaaaaaaaaadwtaoaaaaaaekazlkaaaaav eqzwqaaaadldgrzaacjaxznmaaabi8bfocwaaaaaaaaaaaaaaaaaaaaiqfcf0dabaaa agzmmaaxdgrzagaaaafkt33o5taaaaaaadd6maa0mdn3bztgcv7///8qtjd3iu83dwa azfkaaaaadakaamzmmaaaaaaawoywapw4lnba5jaab7kudgaazfkaaaaaaabkwqaaaa dc5jaa3oywacdnmaahzr9ybqaaanzmmaaabi8bfocwaaaaaaakaaaa3lmcwsa3a1lkd gaiaaaaacuaaaamaaaaaqaaafqaaac0aaaaaaaaaciaaabkaaaalgaaaaeaaaaaaa1c aaanqgaaaaaiaaaaeqaaaewaaaaeaaaaaaaaaaaaaabmaaaaqgaaahaaaabfag0aygb lagqazablagqaiabeag8aywb1ag0azqbuahqaaaagaaaacaaaaayaaaagaaaabgaaaa yaaaagaaaabgaaaamaaaahaaaabgaaaauaaaagaaaacaaaaayaaaagaaaabaaaacuaa aamaaaadqaageyaaaagaaaaegaaaekaywbvag4atwbuagwaeqaaaaaargaaadaaaaak aaaarqbtagiazqbkagqazqbkacaarabvagmadqbtaguabgb0aaaargaaagaaaabuaaa aqwa6afwauabsae8arwbsaeeafgaxafwatqbjaemaugbpafmafgaxafwatwbmagyaaq bjaguamqayafwavwbjae4avwbpafiaraauaeuawabfaaaargaaabaaaaaeaaaaaqaaa eyaaaagaaaaegaaaekaywbvag4atwbuagwaeqaaaaaadgaaabqaaaaaaaaaeaaaabqa aaa="; #endregion using (binarywriter writer = new binarywriter(part.getstream())) { writer.write(system.convert.frombase64string(iconbytes)); writer.flush(); } } }
here code work types, on windows box, requires ole technology. in fact depends on how machine configured, because of ole intimacy, need try bit.
this sample code creates .docx file:
// make sure running in sta thread (for example, mark main stathread attribute) // file want embed string embeddeddocumentpath = @"c:\mypath\myfile.txt"; // temp file created, , embedded in final .docx string packagepath = @"c:\temp\test.bin"; // temp image file created , embedded in final .docx string packageiconpath = @"c:\temp\test.emf"; // package embeddeddocumentpath -> create 2 openxml embeddings packager.packagefile(packagepath, packageiconpath, embeddeddocumentpath); // create word doc using (var doc = wordprocessingdocument.create(@"c:\mypath\containingdocument.docx", wordprocessingdocumenttype.document)) { var main = doc.addmaindocumentpart(); // add icon embedding var imagepart = main.addimagepart(imageparttype.emf); imagepart.feeddata(file.openread(packageiconpath)); // add package embedding var objectpart = main.addembeddedobjectpart("application/vnd.openxmlformats-officedocument.oleobject"); objectpart.feeddata(file.openread(packagepath)); // build sample doc main.document = builddocument(main.getidofpart(imagepart), main.getidofpart(objectpart), "package"); } private static document builddocument(string imagepartid, string objpartid, string progid) { var shapeid = "r" + guid.newguid().tostring("n"); // come unique name... var element = new document( new body( new paragraph(new run(new text("this containing document."))), new paragraph(new run(new text("this embedded document: "))), new paragraph( new run( new embeddedobject( new v.shape( new v.imagedata { relationshipid = imagepartid, // rel image part title = "" // important! }) { id = shapeid }, new ovml.oleobject { type = ovml.olevalues.embed, drawaspect = ovml.oledrawaspectvalues.icon, progid = progid, // com progid id = objpartid, // rel embedded part shapeid = shapeid, // link shape objectid = "r" + guid.newguid().tostring("n") // come unique name... } ))) ) ); return element; } and here utility code create package , image (emf) file input file. now, pdf, code may fail (like said depends if installed adobe reader or not, version, etc.). if fails on olecreatefromfile, may try create/add registry key named 'packageonfiledrop' this:
hkey_classes_root\acroexch.document.dc\packageonfiledrop i'm not sure why pdf files don't support olecreatefromfile directly (undercovers, if have installed acrobat reader, handled acrord32.exe com server provider adobe), think may security feature, , don't know how word circumvents this...
public static class packager { public static void packagefile(string outputfile, string outputimagefile, string inputfile) { if (outputfile == null) throw new argumentnullexception(nameof(outputfile)); if (outputimagefile == null) throw new argumentnullexception(nameof(outputimagefile)); if (inputfile == null) throw new argumentnullexception(nameof(inputfile)); istorage storage; checkhr(stgcreatestorageex( outputfile, stgm_create | stgm_readwrite | stgm_share_exclusive, stgfmt_docfile, 0, intptr.zero, intptr.zero, typeof(istorage).guid, out storage)); // note 1: if 'use of ole1 services requiring dde windows disabled' error, make sure executing thread sta // // note 2: if want packager succeed on pdf files instead of reporting 0x8000ffff (e_unexpected), make sure // there exists key named "packageonfiledrop", this: hkey_classes_root\acroexch.document.dc\packageonfiledrop // idataobject ps; // system.runtime.interopservices.comtypes checkhr(olecreatefromfile( guid.empty, inputfile, typeof(idataobject).guid, 0, intptr.zero, intptr.zero, storage, out ps)); var format = new formatetc(); format.cfformat = cf_enhmetafile; format.dwaspect = dvaspect.dvaspect_content; format.lindex = -1; format.tymed = tymed.tymed_enhmf; stgmedium medium; ps.getdata(ref format, out medium); copyenhmetafile(medium.unionmember, outputimagefile); deleteenhmetafile(medium.unionmember); storage.commit(0); marshal.finalreleasecomobject(ps); marshal.finalreleasecomobject(storage); } private static void checkhr(int hr) { if (hr != 0) throw new win32exception(hr); } [interfacetype(cominterfacetype.interfaceisiunknown), guid("0000000b-0000-0000-c000-000000000046")] private interface istorage { void _vtblgap1_6(); // need commit void commit(int grfcommitflags); } [dllimport("ole32.dll")] private static extern int stgcreatestorageex( [marshalas(unmanagedtype.lpwstr)] string pwcsname, int grfmode, int stgfmt, int grfattrs, intptr pstgoptions, intptr reserved2, [marshalas(unmanagedtype.lpstruct)] guid riid, out istorage ppobjectopen); [dllimport("ole32.dll")] private static extern int olecreatefromfile( [marshalas(unmanagedtype.lpstruct)] guid rclsid, [marshalas(unmanagedtype.lpwstr)] string lpszfilename, [marshalas(unmanagedtype.lpstruct)] guid riid, int renderopt, intptr lpformatetc, intptr pclientsite, istorage pstg, out idataobject ppstg ); [dllimport("gdi32.dll", setlasterror = true)] private static extern bool deleteenhmetafile(intptr hemf); [dllimport("gdi32.dll", charset = charset.unicode, setlasterror = true)] private static extern intptr copyenhmetafile(intptr hemfsrc, string lpszfile); private const int cf_enhmetafile = 14; private const int stgm_readwrite = 2; private const int stgm_share_exclusive = 0x10; private const int stgm_create = 0x1000; private const int stgfmt_docfile = 5; }
Comments
Post a Comment