IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

VB.NET Discussion :

Comment imprimer le contenu d'un Richtextbox avec le format RTF?


Sujet :

VB.NET

  1. #1
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Avril 2008
    Messages
    44
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2008
    Messages : 44
    Points : 26
    Points
    26
    Par défaut Comment imprimer le contenu d'un Richtextbox avec le format RTF?
    Bonjour

    Sur un formulaire, j'ai un Richtextbox dont le texte est mis en forme par programmation au format RTF (police, taille, couleur et centré)

    Jusque là tout va bien, mon texte est affiché conformément à mes attentes.

    J'aimerai imprimer le contenu de mon Richtextbox de manière identique à l'affichage.

    Partout sur le net où j'ai pu trouver quelque chose d'intéressant dans la procédure PrintDocument1_PrintPage, il faudrait mettre l'instruction :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    e.Graphics.DrawString(Me.RichTextBox1.Text, New Font("Arial", 8, FontStyle.Bold), Brushes.Black, 150, 125)
    Or cela m'imprime le text en arial 8 et gras à la position 150, 125.

    Comment transmettre la mise en forme RTF au deuxième paramètre de l'instruction Drawstring.

    Merci pour votre aide

  2. #2
    Expert confirmé
    Inscrit en
    Avril 2008
    Messages
    2 564
    Détails du profil
    Informations personnelles :
    Âge : 64

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 564
    Points : 4 442
    Points
    4 442
    Par défaut Getting WYSIWYG Print Results from a .NET RichTextBox
    bonjour
    obtenir un "WYSIWYG Print" (what you see what you get) ou Tel Quel à l'Impression en francais.
    Voici un UserControl RichTextBoxEx herite de notre ami RichText modifie pour incorporer l'API Win et supportant la mise en page et l'impression à utiliser en remplacement de ton RichTextBox habituel.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
     
    Imports System
    Imports System.Windows.Forms
    Imports System.Drawing
    Imports System.Runtime.InteropServices
    Imports System.Drawing.Printing
     
    ' An extension to RichTextBox suitable for printing
    Public Class RichTextBoxEx
        Inherits RichTextBox
     
        <StructLayout(LayoutKind.Sequential)> _
        Private Structure STRUCT_RECT
            Public left As Int32
            Public top As Int32
            Public right As Int32
            Public bottom As Int32
        End Structure
     
        <StructLayout(LayoutKind.Sequential)> _
        Private Structure STRUCT_CHARRANGE
            Public cpMin As Int32
            Public cpMax As Int32
        End Structure
     
        <StructLayout(LayoutKind.Sequential)> _
        Private Structure STRUCT_FORMATRANGE
            Public hdc As IntPtr
            Public hdcTarget As IntPtr
            Public rc As STRUCT_RECT
            Public rcPage As STRUCT_RECT
            Public chrg As STRUCT_CHARRANGE
        End Structure
     
        <StructLayout(LayoutKind.Sequential)> _
        Private Structure STRUCT_CHARFORMAT
            Public cbSize As Integer
            Public dwMask As UInt32
            Public dwEffects As UInt32
            Public yHeight As Int32
            Public yOffset As Int32
            Public crTextColor As Int32
            Public bCharSet As Byte
            Public bPitchAndFamily As Byte
            <MarshalAs(UnmanagedType.ByValArray, SizeConst:=32)> _
            Public szFaceName() As Char
        End Structure
     
        <DllImport("user32.dll")> _
        Private Shared Function SendMessage(ByVal hWnd As IntPtr, _
                                            ByVal msg As Int32, _
                                            ByVal wParam As Int32, _
                                            ByVal lParam As IntPtr) As Int32
        End Function
     
        ' Windows Message defines
        Private Const WM_USER As Int32 = &H400&
        Private Const EM_FORMATRANGE As Int32 = WM_USER + 57
        Private Const EM_GETCHARFORMAT As Int32 = WM_USER + 58
        Private Const EM_SETCHARFORMAT As Int32 = WM_USER + 68
     
        ' Defines for EM_GETCHARFORMAT/EM_SETCHARFORMAT
        Private SCF_SELECTION As Int32 = &H1&
        Private SCF_WORD As Int32 = &H2&
        Private SCF_ALL As Int32 = &H4&
     
        ' Defines for STRUCT_CHARFORMAT member dwMask
        ' (Long because UInt32 is not an intrinsic type)
        Private Const CFM_BOLD As Long = &H1&
        Private Const CFM_ITALIC As Long = &H2&
        Private Const CFM_UNDERLINE As Long = &H4&
        Private Const CFM_STRIKEOUT As Long = &H8&
        Private Const CFM_PROTECTED As Long = &H10&
        Private Const CFM_LINK As Long = &H20&
        Private Const CFM_SIZE As Long = &H80000000&
        Private Const CFM_COLOR As Long = &H40000000&
        Private Const CFM_FACE As Long = &H20000000&
        Private Const CFM_OFFSET As Long = &H10000000&
        Private Const CFM_CHARSET As Long = &H8000000&
     
        ' Defines for STRUCT_CHARFORMAT member dwEffects
        Private Const CFE_BOLD As Long = &H1&
        Private Const CFE_ITALIC As Long = &H2&
        Private Const CFE_UNDERLINE As Long = &H4&
        Private Const CFE_STRIKEOUT As Long = &H8&
        Private Const CFE_PROTECTED As Long = &H10&
        Private Const CFE_LINK As Long = &H20&
        Private Const CFE_AUTOCOLOR As Long = &H40000000&
     
        ' Calculate or render the contents of our RichTextBox for printing
        '
        ' Parameter "measureOnly": If true, only the calculation is performed,
        '                          otherwise the text is rendered as well
        ' Parameter "e": The PrintPageEventArgs object from the PrintPage event
        ' Parameter "charFrom": Index of first character to be printed
        ' Parameter "charTo": Index of last character to be printed
        ' Return value: (Index of last character that fitted on the page) + 1
        Public Function FormatRange(ByVal measureOnly As Boolean, _
                                    ByVal e As PrintPageEventArgs, _
                                    ByVal charFrom As Integer, _
                                    ByVal charTo As Integer) As Integer
            ' Specify which characters to print
            Dim cr As STRUCT_CHARRANGE
            cr.cpMin = charFrom
            cr.cpMax = charTo
     
            ' Specify the area inside page margins
            Dim rc As STRUCT_RECT
            rc.top = HundredthInchToTwips(e.MarginBounds.Top)
            rc.bottom = HundredthInchToTwips(e.MarginBounds.Bottom)
            rc.left = HundredthInchToTwips(e.MarginBounds.Left)
            rc.right = HundredthInchToTwips(e.MarginBounds.Right)
     
            ' Specify the page area
            Dim rcPage As STRUCT_RECT
            rcPage.top = HundredthInchToTwips(e.PageBounds.Top)
            rcPage.bottom = HundredthInchToTwips(e.PageBounds.Bottom)
            rcPage.left = HundredthInchToTwips(e.PageBounds.Left)
            rcPage.right = HundredthInchToTwips(e.PageBounds.Right)
     
            ' Get device context of output device
            Dim hdc As IntPtr
            hdc = e.Graphics.GetHdc()
     
            ' Fill in the FORMATRANGE structure
            Dim fr As STRUCT_FORMATRANGE
            fr.chrg = cr
            fr.hdc = hdc
            fr.hdcTarget = hdc
            fr.rc = rc
            fr.rcPage = rcPage
     
            ' Non-Zero wParam means render, Zero means measure
            Dim wParam As Int32
            If measureOnly Then
                wParam = 0
            Else
                wParam = 1
            End If
     
            ' Allocate memory for the FORMATRANGE struct and
            ' copy the contents of our struct to this memory
            Dim lParam As IntPtr
            lParam = Marshal.AllocCoTaskMem(Marshal.SizeOf(fr))
            Marshal.StructureToPtr(fr, lParam, False)
     
            ' Send the actual Win32 message
            Dim res As Integer
            res = SendMessage(Handle, EM_FORMATRANGE, wParam, lParam)
     
            ' Free allocated memory
            Marshal.FreeCoTaskMem(lParam)
     
            ' and release the device context
            e.Graphics.ReleaseHdc(hdc)
     
            Return res
        End Function
     
        ' Convert between 1/100 inch (unit used by the .NET framework)
        ' and twips (1/1440 inch, used by Win32 API calls)
        '
        ' Parameter "n": Value in 1/100 inch
        ' Return value: Value in twips
        Private Function HundredthInchToTwips(ByVal n As Integer) As Int32
            Return Convert.ToInt32(n * 14.4)
        End Function
     
        ' Free cached data from rich edit control after printing
        Public Sub FormatRangeDone()
            Dim lParam As New IntPtr(0)
            SendMessage(Handle, EM_FORMATRANGE, 0, lParam)
        End Sub
     
        ' Sets the font only for the selected part of the rich text box
        ' without modifying the other properties like size or style
        ' <param name="face">Name of the font to use</param>
        ' <returns>true on success, false on failure</returns>
        Public Function SetSelectionFont(ByVal face as String) As Boolean
            Dim cf As New STRUCT_CHARFORMAT()
            cf.cbSize = Marshal.SizeOf(cf)
            cf.dwMask = Convert.ToUInt32(CFM_FACE)
     
            ' ReDim face name to relevant size
            ReDim cf.szFaceName(32)
            face.CopyTo(0, cf.szFaceName, 0, Math.Min(31, face.Length))
     
            Dim lParam As IntPtr
            lParam = Marshal.AllocCoTaskMem(Marshal.SizeOf(cf))
            Marshal.StructureToPtr(cf, lParam, False)
     
            Dim res As Integer
            res = SendMessage(Handle, EM_SETCHARFORMAT, SCF_SELECTION, lParam)
            If (res = 0) Then
                Return True
            Else
                Return False
            End If
        End Function
     
        ' Sets the font size only for the selected part of the rich text box
        ' without modifying the other properties like font or style
        ' <param name="size">new point size to use</param>
        ' <returns>true on success, false on failure</returns>
        Public Function SetSelectionSize(ByVal size As Integer) As Boolean
            Dim cf As New STRUCT_CHARFORMAT()
            cf.cbSize = Marshal.SizeOf(cf)
            cf.dwMask = Convert.ToUInt32(CFM_SIZE)
            ' yHeight is in 1/20 pt
            cf.yHeight = size * 20
     
            Dim lParam As IntPtr
            lParam = Marshal.AllocCoTaskMem(Marshal.SizeOf(cf))
            Marshal.StructureToPtr(cf, lParam, False)
     
            Dim res As Integer
            res = SendMessage(Handle, EM_SETCHARFORMAT, SCF_SELECTION, lParam)
            If (res = 0) Then
                Return True
            Else
                Return False
            End If
        End Function
     
        ' Sets the bold style only for the selected part of the rich text box
        ' without modifying the other properties like font or size
        ' <param name="bold">make selection bold (true) or regular (false)</param>
        ' <returns>true on success, false on failure</returns>
        Public Function SetSelectionBold(ByVal bold As Boolean) As Boolean
            If (bold) Then
                Return SetSelectionStyle(CFM_BOLD, CFE_BOLD)
            Else
                Return SetSelectionStyle(CFM_BOLD, 0)
            End If
        End Function
     
        ' Sets the italic style only for the selected part of the rich text box
        ' without modifying the other properties like font or size
        ' <param name="italic">make selection italic (true) or regular (false)</param>
        ' <returns>true on success, false on failure</returns>
        Public Function SetSelectionItalic(ByVal italic As Boolean) As Boolean
            If (italic) Then
                Return SetSelectionStyle(CFM_ITALIC, CFE_ITALIC)
            Else
                Return SetSelectionStyle(CFM_ITALIC, 0)
            End If
        End Function
     
        ' Sets the underlined style only for the selected part of the rich text box
        ' without modifying the other properties like font or size
        ' <param name="underlined">make selection underlined (true) or regular (false)</param>
        ' <returns>true on success, false on failure</returns>
        Public Function SetSelectionUnderlined(ByVal underlined As Boolean) As Boolean
            If (underlined) Then
                Return SetSelectionStyle(CFM_UNDERLINE, CFE_UNDERLINE)
            Else
                Return SetSelectionStyle(CFM_UNDERLINE, 0)
            End If
        End Function
     
        ' Set the style only for the selected part of the rich text box
        ' with the possibility to mask out some styles that are not to be modified
        ' <param name="mask">modify which styles?</param>
        ' <param name="effect">new values for the styles</param>
        ' <returns>true on success, false on failure</returns>
        Private Function SetSelectionStyle(ByVal mask As Int32, ByVal effect As Int32) As Boolean
            Dim cf As New STRUCT_CHARFORMAT()
            cf.cbSize = Marshal.SizeOf(cf)
            cf.dwMask = Convert.ToUInt32(mask)
            cf.dwEffects = Convert.ToUInt32(effect)
     
            Dim lParam As IntPtr
            lParam = Marshal.AllocCoTaskMem(Marshal.SizeOf(cf))
            Marshal.StructureToPtr(cf, lParam, False)
     
            Dim res As Integer
            res = SendMessage(Handle, EM_SETCHARFORMAT, SCF_SELECTION, lParam)
            If (res = 0) Then
                Return True
            Else
                Return False
            End If
        End Function
    End Class
    le code exemple du projet Form qui l'utilse (à remplacer par le form de ton projet ):
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
     
     
    Public Class SampleFrame
        Inherits System.Windows.Forms.Form
     
    #Region " Windows Form Designer generated code "
     
        Public Sub New()
            MyBase.New()
     
            'This call is required by the Windows Form Designer.
            InitializeComponent()
     
            'Add any initialization after the InitializeComponent() call
     
        End Sub
     
        'Form overrides dispose to clean up the component list.
        Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
            If disposing Then
                If Not (components Is Nothing) Then
                    components.Dispose()
                End If
            End If
            MyBase.Dispose(disposing)
        End Sub
     
        'Required by the Windows Form Designer
        Private components As System.ComponentModel.IContainer
     
        'NOTE: The following procedure is required by the Windows Form Designer
        'It can be modified using the Windows Form Designer.  
        'Do not modify it using the code editor.
        Friend WithEvents richTextBoxEx1 As RichTextBoxEx
        Friend WithEvents MenuFile As System.Windows.Forms.MenuItem
        Friend WithEvents MenuFormat As System.Windows.Forms.MenuItem
        Friend WithEvents MenuFilePageSetup As System.Windows.Forms.MenuItem
        Friend WithEvents MenuFilePrintPreview As System.Windows.Forms.MenuItem
        Friend WithEvents MenuFilePrint As System.Windows.Forms.MenuItem
        Friend WithEvents MenuFormatBold As System.Windows.Forms.MenuItem
        Friend WithEvents MenuFormatItalic As System.Windows.Forms.MenuItem
        Friend WithEvents MenuFormatUnderlined As System.Windows.Forms.MenuItem
        Friend WithEvents MenuFontSize As System.Windows.Forms.MenuItem
        Friend WithEvents MenuFont As System.Windows.Forms.MenuItem
        Friend WithEvents MenuFontSize8 As System.Windows.Forms.MenuItem
        Friend WithEvents MenuFontSize10 As System.Windows.Forms.MenuItem
        Friend WithEvents MainMenu1 As System.Windows.Forms.MainMenu
        Friend WithEvents MenuFontSize12 As System.Windows.Forms.MenuItem
        Friend WithEvents MenuFontSize18 As System.Windows.Forms.MenuItem
        Friend WithEvents MenuFontSize24 As System.Windows.Forms.MenuItem
        Friend WithEvents MenuFontArial As System.Windows.Forms.MenuItem
        Friend WithEvents MenuFontCourier As System.Windows.Forms.MenuItem
        Friend WithEvents MenuFontTimes As System.Windows.Forms.MenuItem
        Friend WithEvents PrintDocument1 As System.Drawing.Printing.PrintDocument
        Friend WithEvents PageSetupDialog1 As System.Windows.Forms.PageSetupDialog
        Friend WithEvents PrintPreviewDialog1 As System.Windows.Forms.PrintPreviewDialog
        Friend WithEvents PrintDialog1 As System.Windows.Forms.PrintDialog
        <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
            Me.components = New System.ComponentModel.Container
            Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(SampleFrame))
            Me.MainMenu1 = New System.Windows.Forms.MainMenu(Me.components)
            Me.MenuFile = New System.Windows.Forms.MenuItem
            Me.MenuFilePageSetup = New System.Windows.Forms.MenuItem
            Me.MenuFilePrintPreview = New System.Windows.Forms.MenuItem
            Me.MenuFilePrint = New System.Windows.Forms.MenuItem
            Me.MenuFormat = New System.Windows.Forms.MenuItem
            Me.MenuFormatBold = New System.Windows.Forms.MenuItem
            Me.MenuFormatItalic = New System.Windows.Forms.MenuItem
            Me.MenuFormatUnderlined = New System.Windows.Forms.MenuItem
            Me.MenuFontSize = New System.Windows.Forms.MenuItem
            Me.MenuFontSize8 = New System.Windows.Forms.MenuItem
            Me.MenuFontSize10 = New System.Windows.Forms.MenuItem
            Me.MenuFontSize12 = New System.Windows.Forms.MenuItem
            Me.MenuFontSize18 = New System.Windows.Forms.MenuItem
            Me.MenuFontSize24 = New System.Windows.Forms.MenuItem
            Me.MenuFont = New System.Windows.Forms.MenuItem
            Me.MenuFontArial = New System.Windows.Forms.MenuItem
            Me.MenuFontCourier = New System.Windows.Forms.MenuItem
            Me.MenuFontTimes = New System.Windows.Forms.MenuItem
            Me.PrintDocument1 = New System.Drawing.Printing.PrintDocument
            Me.PageSetupDialog1 = New System.Windows.Forms.PageSetupDialog
            Me.PrintPreviewDialog1 = New System.Windows.Forms.PrintPreviewDialog
            Me.PrintDialog1 = New System.Windows.Forms.PrintDialog
            Me.richTextBoxEx1 = New RichTextBoxEx
            Me.SuspendLayout()
            '
            'MainMenu1
            '
            Me.MainMenu1.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.MenuFile, Me.MenuFormat})
            '
            'MenuFile
            '
            Me.MenuFile.Index = 0
            Me.MenuFile.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.MenuFilePageSetup, Me.MenuFilePrintPreview, Me.MenuFilePrint})
            Me.MenuFile.Text = "&File"
            '
            'MenuFilePageSetup
            '
            Me.MenuFilePageSetup.Index = 0
            Me.MenuFilePageSetup.Text = "Page &Setup..."
            '
            'MenuFilePrintPreview
            '
            Me.MenuFilePrintPreview.Index = 1
            Me.MenuFilePrintPreview.Text = "Print Pre&view..."
            '
            'MenuFilePrint
            '
            Me.MenuFilePrint.Index = 2
            Me.MenuFilePrint.Text = "&Print..."
            '
            'MenuFormat
            '
            Me.MenuFormat.Index = 1
            Me.MenuFormat.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.MenuFormatBold, Me.MenuFormatItalic, Me.MenuFormatUnderlined, Me.MenuFontSize, Me.MenuFont})
            Me.MenuFormat.Text = "F&ormat"
            '
            'MenuFormatBold
            '
            Me.MenuFormatBold.Index = 0
            Me.MenuFormatBold.Text = "&Bold"
            '
            'MenuFormatItalic
            '
            Me.MenuFormatItalic.Index = 1
            Me.MenuFormatItalic.Text = "&Italic"
            '
            'MenuFormatUnderlined
            '
            Me.MenuFormatUnderlined.Index = 2
            Me.MenuFormatUnderlined.Text = "&Underlined"
            '
            'MenuFontSize
            '
            Me.MenuFontSize.Index = 3
            Me.MenuFontSize.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.MenuFontSize8, Me.MenuFontSize10, Me.MenuFontSize12, Me.MenuFontSize18, Me.MenuFontSize24})
            Me.MenuFontSize.Text = "Font &Size"
            '
            'MenuFontSize8
            '
            Me.MenuFontSize8.Index = 0
            Me.MenuFontSize8.Text = "8"
            '
            'MenuFontSize10
            '
            Me.MenuFontSize10.Index = 1
            Me.MenuFontSize10.Text = "10"
            '
            'MenuFontSize12
            '
            Me.MenuFontSize12.Index = 2
            Me.MenuFontSize12.Text = "12"
            '
            'MenuFontSize18
            '
            Me.MenuFontSize18.Index = 3
            Me.MenuFontSize18.Text = "18"
            '
            'MenuFontSize24
            '
            Me.MenuFontSize24.Index = 4
            Me.MenuFontSize24.Text = "24"
            '
            'MenuFont
            '
            Me.MenuFont.Index = 4
            Me.MenuFont.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.MenuFontArial, Me.MenuFontCourier, Me.MenuFontTimes})
            Me.MenuFont.Text = "&Font"
            '
            'MenuFontArial
            '
            Me.MenuFontArial.Index = 0
            Me.MenuFontArial.Text = "Arial"
            '
            'MenuFontCourier
            '
            Me.MenuFontCourier.Index = 1
            Me.MenuFontCourier.Text = "Courier"
            '
            'MenuFontTimes
            '
            Me.MenuFontTimes.Index = 2
            Me.MenuFontTimes.Text = "Times New Roman"
            '
            'PrintDocument1
            '
            '
            'PageSetupDialog1
            '
            Me.PageSetupDialog1.Document = Me.PrintDocument1
            '
            'PrintPreviewDialog1
            '
            Me.PrintPreviewDialog1.AutoScrollMargin = New System.Drawing.Size(0, 0)
            Me.PrintPreviewDialog1.AutoScrollMinSize = New System.Drawing.Size(0, 0)
            Me.PrintPreviewDialog1.ClientSize = New System.Drawing.Size(400, 300)
            Me.PrintPreviewDialog1.Document = Me.PrintDocument1
            Me.PrintPreviewDialog1.Enabled = True
            Me.PrintPreviewDialog1.Icon = CType(resources.GetObject("PrintPreviewDialog1.Icon"), System.Drawing.Icon)
            Me.PrintPreviewDialog1.Name = "PrintPreviewDialog1"
            Me.PrintPreviewDialog1.Visible = False
            '
            'PrintDialog1
            '
            Me.PrintDialog1.Document = Me.PrintDocument1
            '
            'richTextBoxEx1
            '
            Me.richTextBoxEx1.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
                        Or System.Windows.Forms.AnchorStyles.Left) _
                        Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
            Me.richTextBoxEx1.Location = New System.Drawing.Point(0, 0)
            Me.richTextBoxEx1.Name = "richTextBoxEx1"
            Me.richTextBoxEx1.Size = New System.Drawing.Size(484, 210)
            Me.richTextBoxEx1.TabIndex = 0
            Me.richTextBoxEx1.Text = ""
            '
            'SampleFrame
            '
            Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
            Me.ClientSize = New System.Drawing.Size(480, 204)
            Me.Controls.Add(Me.richTextBoxEx1)
            Me.Menu = Me.MainMenu1
            Me.Name = "SampleFrame"
            Me.Text = "RichTextBoxEx Sample (VB.NET)"
            Me.ResumeLayout(False)
     
        End Sub
     
    #End Region
     
        Private m_nFirstCharOnPage As Integer
     
        Private Sub PrintDocument1_BeginPrint(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintEventArgs) Handles PrintDocument1.BeginPrint
            ' Start at the beginning of the text
            m_nFirstCharOnPage = 0
        End Sub
     
        Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
            ' To print the boundaries of the current page margins
            ' uncomment the next line:
            e.Graphics.DrawRectangle(System.Drawing.Pens.Blue, e.MarginBounds)
     
            ' make the RichTextBoxEx calculate and render as much text as will
            ' fit on the page and remember the last character printed for the
            ' beginning of the next page
            m_nFirstCharOnPage = richTextBoxEx1.FormatRange(False, _
                                                    e, _
                                                    m_nFirstCharOnPage, _
                                                    richTextBoxEx1.TextLength)
     
            ' check if there are more pages to print
            If (m_nFirstCharOnPage < richTextBoxEx1.TextLength) Then
                e.HasMorePages = True
            Else
                e.HasMorePages = False
            End If
        End Sub
     
        Private Sub PrintDocument1_EndPrint(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintEventArgs) Handles PrintDocument1.EndPrint
            ' Clean up cached information
            richTextBoxEx1.FormatRangeDone()
        End Sub
     
        Private Sub MenuFilePageSetup_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuFilePageSetup.Click
            PageSetupDialog1.ShowDialog()
        End Sub
     
        Private Sub MenuFilePrintPreview_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuFilePrintPreview.Click
            If (PrintPreviewDialog1.ShowDialog = DialogResult.OK) Then
                PrintDocument1.Print()
            End If
        End Sub
     
        Private Sub MenuFilePrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuFilePrint.Click
            PrintDocument1.Print()
        End Sub
     
        Private Sub MenuFormatBold_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuFormatBold.Click
            richTextBoxEx1.SetSelectionBold(True)
        End Sub
     
        Private Sub MenuFormatItalic_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuFormatItalic.Click
            richTextBoxEx1.SetSelectionItalic(True)
        End Sub
     
        Private Sub MenuFormatUnderlined_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuFormatUnderlined.Click
            richTextBoxEx1.SetSelectionUnderlined(True)
        End Sub
     
        Private Sub MenuFontSize8_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuFontSize8.Click
            richTextBoxEx1.SetSelectionSize(8)
        End Sub
     
        Private Sub MenuFontSize10_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuFontSize10.Click
            richTextBoxEx1.SetSelectionSize(10)
        End Sub
     
        Private Sub MenuFontSize12_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuFontSize12.Click
            richTextBoxEx1.SetSelectionSize(12)
        End Sub
     
        Private Sub MenuFontSize18_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuFontSize18.Click
            richTextBoxEx1.SetSelectionSize(18)
        End Sub
     
        Private Sub MenuFontSize24_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuFontSize24.Click
            richTextBoxEx1.SetSelectionSize(24)
        End Sub
     
        Private Sub MenuFontArial_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuFontArial.Click
            richTextBoxEx1.SetSelectionFont("Arial")
        End Sub
     
        Private Sub MenuFontCourier_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuFontCourier.Click
            richTextBoxEx1.SetSelectionFont("Courier New")
        End Sub
     
        Private Sub MenuFontTimes_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuFontTimes.Click
            richTextBoxEx1.SetSelectionFont("Times New Roman")
        End Sub
    End Class
    utilisation :
    ->tu ajoutes le projet RTBExVB et genere(pour l'avoir le control dans boite à outil)
    ->tu ajoute les controles suivants sur ton form:
    -PrintDocument ,PageSetupDialog,PrintPreviewDialog,PrintDialog
    -le controle richtextboxEx

    Pour information il vient de chez MSDN sur ce lien:
    mhtml:file://D:\PojetForum\Utilitair.../ms996492.aspx
    tu trouveras le code ci-dessus
    bon code.....

  3. #3
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Avril 2008
    Messages
    44
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2008
    Messages : 44
    Points : 26
    Points
    26
    Par défaut
    Merci, Mabrouki

    Wouahou, c'est balaise.

    Si j'ai bien compris, il faut créer une application qui crée un nouveau controle hérité de Richtextbox et ajouter ce nouveau controle dans mon projet.

    Donc le controle Richtextbox de VB n'accepte pas l'impression en WYSIWYG.

    Je suis retourné sur le net et il n'y a rien de plus simple que ce que tu propose. Merci encore

  4. #4
    Expert confirmé
    Inscrit en
    Avril 2008
    Messages
    2 564
    Détails du profil
    Informations personnelles :
    Âge : 64

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 564
    Points : 4 442
    Points
    4 442
    Par défaut RichTextBoxEx
    Bonjour

    Il suffit simplemement de l'ajouter comme un projet en plus dans ta solution et de le generer pour le voir apparaitre dans la boite à outils.
    tu le droppe sur ta forme (tu n'utilise plus l'ancetre car il a les memes proprietes que l'ancetre en plus l'impression).
    bon code...

  5. #5
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Avril 2008
    Messages
    44
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2008
    Messages : 44
    Points : 26
    Points
    26
    Par défaut
    Et pourquoi ne pas ajouter l'impression à l'ancêtre?

    Est-ce possible?

  6. #6
    Expert éminent Avatar de Graffito
    Profil pro
    Inscrit en
    Janvier 2006
    Messages
    5 993
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2006
    Messages : 5 993
    Points : 7 903
    Points
    7 903
    Par défaut
    Bonjour,

    Tu trouveras ci-dessopus une autre solution pour imprimer un document comme avec un click-droit sur l'explorateur de fichiers.
    Restrictions :
    - On ne peut pas avoir accès aux propriétés de l'imprimante.
    - le choix de l'imprimante est possible, mais il faut se programmer le menu de choix.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
     
    // on sauvegarde le rtf dans un fichier que l'on met dans le répertoire temporaire     
    // de windows et on utilise la fonction ci-dessous pour l'imprimer: 
     
        internal static bool PrintDocument(string FileName,string PrinterName)
        { // PrinterName= ""(Default) / "?" (select printer dialog) / xxxx
          bool Result=false ;
          if (PrinterName!="") PrinterName=SelectPrinterDialog(PrinterName) ;
          if (PrinterName!=null)
          {
            if (!System.IO.File.Exists(FileName)) 
             MessageBox.Show("File to be printed was not found : "+FileName) ;
            else 
            {
              System.Diagnostics.Process TheProcess = new System.Diagnostics.Process() ;
              try
             { 
                TheProcess.StartInfo.FileName = FileName ;
                TheProcess.StartInfo.Verb     = PrinterName==""?"Print":"Printto" ;
                TheProcess.StartInfo.Arguments= PrinterName ;
                TheProcess.StartInfo.CreateNoWindow = true ;
                TheProcess.Start() ;
                Result=true ;
             }
              catch (Exception Ex) { MessageBox.Show("File print error on "+
                    FileName+Environment.NewLine+Ex.Message.ToString()) ; }
            }
          }
          return Result ;
        }
     
        internal static string SelectPrinterDialog(string PreferedPrinterName) 
        { // if PreferedPrinterName= "" : Returns Default Printer
          // returns null, if CANCEL during printer selection 
          string Result="-" ;
          if (PrinterSettings.InstalledPrinters.Count==0) MessageBox.Show("No printer available") ; 
          else 
          {
            bool PrinterOk=PreferedPrinterName=="" ;
            string DefaultPrinterName = new PrintDocument().PrinterSettings.PrinterName ;
            if (PrinterOk) Result=DefaultPrinterName ;
            else foreach (string s in PrinterSettings.InstalledPrinters) if (s==PreferedPrinterName) PrinterOk=true ;
            if (!PrinterOk) 
            {
              // ... Intégrer ici un menu de choix parmi les imprimantes
              // ... Exemple : Result=PrinterSettings.InstalledPrinters2]
          }
          return Result ;
        }
    Pour imprimer en paysage, il faut modifier le texte rtf ainsi:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
    RtfText.Insert(RtfText.IndexOf("{\\rtf1\\")+"{\\rtf1\\".Length,
            "lndscpsxn\\vern16469\\paperw16838\\paperh11906\\margl1000\\margr1000\\margt1000\\margb1000\\"

  7. #7
    Expert confirmé
    Inscrit en
    Avril 2008
    Messages
    2 564
    Détails du profil
    Informations personnelles :
    Âge : 64

    Informations forums :
    Inscription : Avril 2008
    Messages : 2 564
    Points : 4 442
    Points
    4 442
    Par défaut RichTextBoxEx
    bonjour
    je pense que microsoft n'en veut pas et nous pousse à programmer avec le WPF.(sortie par la SVP ou c'est ecrit WPF...).
    Dans les winforms de WPF il suffit de mettre un controle Page ,un controle RichTextBox et un controle DocumentViewer et la corvee est liquidee..avec un "look 2011 ou 2015" .
    exemple :
    code xaml à coller dans le concepteur Winform du projet appli WPF(par dessus le code xaml existant) :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
     
     
    <Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      x:Class="SaveLoadPrintRTB" >
     
        <StackPanel>
            <RichTextBox Name="richTB">
                <FlowDocument>
                    <Paragraph>
                        <Run>Paragraph 1 tapes quelque chose codeur
                        et fais un save .Ensuite fais un Load... </Run>
                    </Paragraph>
                    <Paragraph>
                        <Run>Paragraph 2 ou bien prends un contenu msword et colle le ici..et fais un save..et reload</Run>
                    </Paragraph>
     
                </FlowDocument>
            </RichTextBox>
     
            <Button Click="SaveRTBContent">Save RTB Content</Button>
            <Button Click="LoadRTBContent">Load RTB Content</Button>
            <Button Click="PrintRTBContent">Print RTB Content</Button>
        </StackPanel>
     
    </Page>
    code behind de la forme:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
     
     
     
    Imports System
    Imports System.IO
    Imports System.Windows
    Imports System.Windows.Controls
    Imports System.Windows.Media
    Imports System.Windows.Documents
     
    Partial Public Class SaveLoadPrintRTB
        Inherits Page
        Private CheminFichier As String = Directory.GetCurrentDirectory & "\memo.xaml"
        'Handle "Load RichTextBox Content" button click.
        Private Sub LoadRTBContent(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
            ' Send URL string specifying what file to retrieve XAML
            ' from to load into the RichTextBox.
            LoadXamlPackage(CheminFichier)
        End Sub
        ' Handle "Print RichTextBox Content" button click.
        Private Sub PrintRTBContent(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
            PrintCommand()
        End Sub
        'Handle "Save RichTextBox Content" button click.
        Private Sub SaveRTBContent(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
            ' Send an arbitrary URL and file name string specifying
            ' the location to save the XAML in.
            SaveXamlPackage(CheminFichier)
        End Sub
        ' Save XAML in RichTextBox to a file specified by _fileName
        Private Sub SaveXamlPackage(ByVal _fileName As String)
     
     
            Dim range As TextRange
            Dim fStream As FileStream
            range = New TextRange(richTB.Document.ContentStart, richTB.Document.ContentEnd)
            fStream = New FileStream(_fileName, FileMode.Create)
            range.Save(fStream, DataFormats.XamlPackage)
            fStream.Close()
        End Sub
        'Load XAML into RichTextBox from a file specified by _fileName
        Private Sub LoadXamlPackage(ByVal _fileName As String)
            Dim range As TextRange
            Dim fStream As FileStream
            If (File.Exists(_fileName)) Then
     
                range = New TextRange(richTB.Document.ContentStart, richTB.Document.ContentEnd)
                fStream = New FileStream(_fileName, FileMode.OpenOrCreate)
                range.Load(fStream, DataFormats.XamlPackage)
                fStream.Close()
            End If
        End Sub
        ' Print RichTextBox content
        Private Sub PrintCommand()
            Dim pd As PrintDialog = New PrintDialog()
            If (pd.ShowDialog()) Then
     
                'use either one of the below      
                pd.PrintVisual(CType(richTB, Visual), "printing as visual")
                pd.PrintDocument(CType(richTB.Document, IDocumentPaginatorSource).DocumentPaginator, "printing as paginator")
            End If
        End Sub
     
     
    End Class
    et execute ...teste
    bon code....

  8. #8
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Avril 2008
    Messages
    44
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2008
    Messages : 44
    Points : 26
    Points
    26
    Par défaut
    Merci à tous pour votre aide.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Réponses: 2
    Dernier message: 18/06/2014, 09h34
  2. Comment imprimer le contenu d'un richtextbox?
    Par mat.net dans le forum Windows Forms
    Réponses: 1
    Dernier message: 22/12/2009, 22h37
  3. [C#] Imprimer le contenu d'une fenêtre avec ascenseur
    Par biglong dans le forum Windows Forms
    Réponses: 6
    Dernier message: 06/08/2007, 23h29
  4. [Delphi 6] Comment imprimer le contenu d'un TStringGrid ?
    Par bobstar dans le forum Composants VCL
    Réponses: 6
    Dernier message: 22/09/2005, 18h43
  5. Comment imprimer le contenu d'un TStringGrid
    Par scorpiwolf dans le forum C++Builder
    Réponses: 2
    Dernier message: 19/06/2002, 15h41

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo