odf2xml 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #!/usr/bin/python3
  2. # -*- coding: utf-8 -*-
  3. # Copyright (C) 2008 Søren Roug, European Environment Agency
  4. #
  5. # This is free software. You may redistribute it under the terms
  6. # of the Apache license and the GNU General Public License Version
  7. # 2 or at your option any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public
  15. # License along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. #
  18. # Contributor(s):
  19. #
  20. #
  21. # OpenDocument can be a complete office document in a single
  22. # XML document. This script will create such a document.
  23. import sys, getopt, base64
  24. from odf.opendocument import load
  25. from odf.draw import Image, ObjectOle
  26. from odf.style import BackgroundImage
  27. from odf.text import ListLevelStyleImage
  28. from odf.office import BinaryData
  29. if sys.version_info[0]==3: unicode=str
  30. def usage():
  31. sys.stderr.write("Usage: %s [-e] [-o outputfile] [inputfile]\n" % sys.argv[0])
  32. if __name__ == "__main__":
  33. embedimage = False
  34. try:
  35. opts, args = getopt.getopt(sys.argv[1:], "o:e", ["output="])
  36. except getopt.GetoptError:
  37. usage()
  38. sys.exit(2)
  39. outputfile = '-'
  40. for o, a in opts:
  41. if o in ("-o", "--output"):
  42. outputfile = a
  43. if o == '-e':
  44. embedimage = True
  45. if len(args) > 1:
  46. usage()
  47. sys.exit(2)
  48. if len(args) == 0:
  49. d = load(sys.stdin)
  50. else:
  51. d = load(unicode(args[0]))
  52. if embedimage:
  53. images = d.getElementsByType(Image) + \
  54. d.getElementsByType(BackgroundImage) + \
  55. d.getElementsByType(ObjectOle) + \
  56. d.getElementsByType(ListLevelStyleImage)
  57. for image in images:
  58. href = image.getAttribute('href')
  59. if href and href[:9] == "Pictures/":
  60. p = d.Pictures[href]
  61. bp = base64.encodestring(p[1])
  62. image.addElement(BinaryData(text=bp))
  63. image.removeAttribute('href')
  64. xml = d.xml()
  65. if outputfile == '-':
  66. print (xml)
  67. else:
  68. open(outputfile,"wb").write(xml)
  69. # Local Variables: ***
  70. # mode: python ***
  71. # End: ***