Skip to content

feature: character style #17

Closed
Closed

Description

@vakano

Hi,Scanny,

Is there any way to change font, size, color or style of a paragraph or a character?

Activity

  1. scanny commented on Feb 28, 2014

    @scanny
    Contributor

    The documentation is available here.

    The Paragaph.style attribute allows a paragraph style to be applied. The font typeface, size, and color can all be specified in a paragraph style.

    There is not yet a way to apply a character style to a run. That will be an important and useful feature.

    There is also not yet a direct way to manipulate a style in python-docx. That may also turn out to be an important feature.

    A way to apply character formatting directly to a run will probably be last of these to come, since the effect can be achieved by defining a character style and applying it.

  2. vakano commented on Mar 4, 2014

    @vakano
    Author

    thanks for the feedback, so does it mean we can not set a paragraph to this specific example for current ? font(eg:Calibri) size(eg:10.5) color(eg red).

    BTW: I am not clear about the meanning of "a run", can you give some explanations?

  3. scanny commented on Mar 4, 2014

    @scanny
    Contributor

    A run is a sequence of characters within a paragraph that share the same character formatting. So a single bold word in a paragraph would be in a separate run. That paragraph would need three runs, containing the text before the bold word, the text of the bold word, and the text after the bold word respectively.

    You should be able to achieve the effect you're describing by creating a style in the "template" document you're using that has the font characteristics you want and then applying that paragraph style to the paragraph.

  4. scanny commented on Apr 5, 2014

    @scanny
    Contributor

    @vrvolle In the XML, applying a style to a run (a character style) looks like this:

          <w:r>
            <w:rPr>
              <w:rStyle w:val="Emphasis"/>
            </w:rPr>
            <w:t>words with character style applied</w:t>
          </w:r>

    If you're willing to go with a workaround until this can be implemented, something like this should do the trick:

    from docx.oxml.shared import OxmlElement, qn
    
    run = paragraph.add_run('words to emphasize')
    rPr = run._r.get_or_add_rPr()
    rStyle = OxmlElement('w:rStyle')
    rStyle.set(qn('w:val'), 'Emphasis')
    rPr.insert(0, rStyle)

    I haven't tested this, so let me know if it gives you trouble and I can help you troubleshoot.

    You'll need to discover the actual character style names by looking them up in the styles.xml of the document or by guessing. They should match the GUI names for the styles, but with spaces collapsed and capitalization possibly different.

    An easy way to browse the styles.xml is by using opc-diag.

    Let me know if you need more.

  5. kontrafiktion commented on Apr 7, 2014

    @kontrafiktion

    works like a charm
    thx

  6. kontrafiktion commented on Apr 7, 2014

    @kontrafiktion

    I cloned the repo and tried to run

    python setup.py test
    

    but it runs 0 tests:

    running test
    running egg_info
    writing requirements to python_docx.egg-info/requires.txt
    writing python_docx.egg-info/PKG-INFO
    writing top-level names to python_docx.egg-info/top_level.txt
    writing dependency_links to python_docx.egg-info/dependency_links.txt
    reading manifest file 'python_docx.egg-info/SOURCES.txt'
    reading manifest template 'MANIFEST.in'
    writing manifest file 'python_docx.egg-info/SOURCES.txt'
    running build_ext
    
    ----------------------------------------------------------------------
    Ran 0 tests in 0.000s
    
    OK
    

    What do I have to do, if I want to start hacking the module (I am very new to Python, but wanted to give it a try)

  7. kontrafiktion commented on Apr 7, 2014

    @kontrafiktion

    this seems to work: invoking

    py.test
    

    in the 'tests' directory.

    B.t.w.: running py.test-3.4 results in a tremendous bunch of errors. Mostly

    AttributeError: 'method-wrapper' object has no attribute '__module__'
    
  8. scanny commented on Apr 7, 2014

    @scanny
    Contributor

    should run py.test in the main python-docx dir

    Also behave

    so:

    $ cd python-docx
    
    $ py.test
    ... 551 tests
    
    $ behave
    ... 126 scenarios passed ...
  9. kontrafiktion commented on Apr 7, 2014

    @kontrafiktion

    Thx.

    I have started to create a patch at https://github.com/vrvolle/python-docx/tree/character-style

    It is already working. I just copied the implementation for pStyle (though I didn't like the code duplication and having to work through "Run", "CT_R" and "CT_RPr" -- but as I said, I am very new to Python). What I really don't understand: why in one place there is

     pStyle.get(qn('w:val'))
    

    to access the value and

     self.pStyle.val
    

    at another.

    Still missing: tests and documentation (try to finish until end of week).

  10. scanny commented on Apr 7, 2014

    @scanny
    Contributor

    Yep, that former one could be changed to look like the latter. Probably just an artifact of coding sequence. I've been a little loose with the .oxml subpackages because most of that code will be replaced by declarations that drive a configurable metaclass, once I get caught up a little further and can go heads down on that architectural bit :)

    Looks great so far, never mind the seeming duplication, most or all of that part will get swallowed up by the metaprogramming once I'm done :)

  11. kontrafiktion commented on Apr 24, 2014

    @kontrafiktion

    "Looks great so far, never mind the seeming duplication, most or all of that part will get swallowed up by the metaprogramming once I'm done :)"

    I need some more features (cross references, footnotes -- everything needed for multimarkdown). Should I wait for you to be done or start hacking?

    How do you want to change the impl. with metaprogramming, via __getattr__ magic or by using decorators extensively? Just curious.

  12. scanny commented on Apr 24, 2014

    @scanny
    Contributor

    Hi Victor, were you going to add an acceptance test for that feature? I think that's the only part outstanding on the character styles. This acceptance test is pretty close as an example: https://github.com/python-openxml/python-docx/blob/master/features/par-set-style.feature
    and uses these steps: https://github.com/python-openxml/python-docx/blob/master/features/steps/paragraph.py.

    Happy to have you work on other features. Best to start with determining the API. I use a page like this one in the developer documentation to get that sorted out: http://python-docx.readthedocs.org/en/latest/dev/analysis/features/breaks.html. Once you have a proposal there we can discuss and resolve. Then I start with a failing acceptance test. Both of these are separately committable steps even if there's no implementation.

    Some folks like to spike then, to get the implementation working. But ultimately the work product that's the least work for me to commit (read: fastest time from pull request to commit) is working outside in, one test at a time. Here's a fairly typical example, the four commits starting with this one for adding the .bold property to a run: d04bbd0.

    On the metaprogramming bit, what I had planned to do was add methods to a given class for the particular child elements and attributes it had, based on a declarative definition in the class. Roughly like what SQLAlchemy or Django does. So it would be something like:

    class CT_Paragraph(BaseOxmlElement):
        pPr = ChildElement(CT_ParagraphProperties, ...)
        ...

    which would produce a class that had the following properties and methods:

    p = CT_Paragraph.new()
    p.pPr
    p.get_or_add_pPr()
    p._add_pPr()
    p.remove_pPr()

    The properties and methods would include ones for each child element and attribute, so it would get to be something of a long list. Implementations would generally be with standard closures define in or around the MetaClass.

    That's the idea going in anyway, so it would basically replace all the hand-coded methods in the oxml sub-package with declarations of the right types.

  13. kontrafiktion commented on Apr 27, 2014

    @kontrafiktion

    done

  14. modified the milestones: , on May 1, 2014
  15. scanny commented on May 1, 2014

    @scanny
    Contributor

    SchwEEEt! Incorporating now ...

  16. added a commit that references this issue on May 7, 2014
  17. scanny commented on May 7, 2014

    @scanny
    Contributor

    Committed to master and develop and released to PyPI as v0.5.2.

  18. scanny commented on May 7, 2014

    @scanny
    Contributor

    @vrvolle Can you contact me via email at stcanny at geemail dot com? There are a few things about the commits I wanted to discuss with you if you have a minute.

  19. modified the milestones: v0.5.2, on May 8, 2014
  20. Maginx commented on Dec 30, 2015

    @Maginx

    Hi,

    I used this API to write word document, but I find I set the font name is not effectual to Chinese characters. Do you have any resolution?

    code snippet :
    title = docx.add_paragraph(unicode(article.title.content,'gbk'))
    title_run = title.runs[0]
    parag_format = title.paragraph_format
    title.line_spacing_rule = WD_LINE_SPACING.MULTIPLE
    parag_format.alignment = TITLE_STYLE
    parag_format.line_spacing = TITLE_PARA_STYLE
    title_run.font.name = TITLE_FONT_NAME
    title_run.font.size = Pt(TITLE_FONT_SIZE)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions