Asymmetric shapes and evidence for binary central stars suggest a common-envelope origin for many bipolar planetary nebulae. The bipolar components of the nebulae are observed to expand faster than the rest, and the more slowly expanding material has been associated with the bulk of the envelope ejected during the common-envelope phase of a stellar binary system. Common-envelope evolution in general remains one of the biggest uncertainties in binary star evolution, and the origin of the fast outflow has not been explained satisfactorily. We perform three-dimensional magnetohydrodynamic simulations of common-envelope interaction with the moving-mesh code AREPO. Starting from the plunge-in of the companion into the envelope of an asymptotic-giant-branch star and covering hundreds of orbits of the binary star system, we are able to follow the evolution to complete envelope ejection. We find that magnetic fields are strongly amplified in two consecutive episodes: first, when the companion spirals in the envelope and, second, when it forms a contact binary with the core of the former giant star. In the second episode, a magnetically driven, high-velocity outflow of gas is launched self-consistently in our simulations. The outflow is bipolar, and the gas is additionally collimated by the ejected common envelope. The resulting structure reproduces typical morphologies and velocities observed in young planetary nebulae. We propose that the magnetic driving mechanism is a universal consequence of common-envelope interaction that is responsible for a substantial fraction of observed planetary nebulae. Such a mechanism likely also exists in the common-envelope phase of other binary stars that lead to the formation of Type Ia supernovae, X-ray binaries, and gravitational-wave merger events.